Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 处理阵列的有效方法_Arrays_Sorting_Computer Science_Performance - Fatal编程技术网

Arrays 处理阵列的有效方法

Arrays 处理阵列的有效方法,arrays,sorting,computer-science,performance,Arrays,Sorting,Computer Science,Performance,假设我有以下数组 数组1:城市列表(可能有一些与数组2相同的条目) 数组2:城市列表 我想输出以下列表: 仅在数组1中列出城市 仅在数组2中列出城市 两个阵列中的城市列表 完成1-3的最有效方式是什么 我想在每个数组中存储城市的名称,然后进行foreach比较两者。如果对数组进行排序,则可以并行遍历它们: index_1 = 0 // assuming zero based indexing index_2 = 0 repeat the follwoing loop: if( index_0

假设我有以下数组

数组1:城市列表(可能有一些与数组2相同的条目) 数组2:城市列表

我想输出以下列表:

  • 仅在数组1中列出城市
  • 仅在数组2中列出城市
  • 两个阵列中的城市列表
  • 完成1-3的最有效方式是什么


    我想在每个数组中存储城市的名称,然后进行foreach比较两者。

    如果对数组进行排序,则可以并行遍历它们:

    index_1 = 0 // assuming zero based indexing
    index_2 = 0
    
    repeat the follwoing loop:
    if( index_0 is out of range )
      count (remaining) cities from array 2
    else if( index_1 is out of range )
      count (remaining) cities from array 2
    else {
    a = get city from array 1 with the index_1
    b = get city from array 2 with the index_2
    if( a = b ) {
      increment no. of cities in both arrays
      increment both indices
    }
    else if( a < b )
      count cities from array 1 until city from array 2 is b, update indices
    else 
      count cities from array 2 until city from array 1 is a, update indices
    }
    end loop
    
    index_1=0//假设基于零的索引
    指数_2=0
    重复以下循环:
    如果(索引_0超出范围)
    从阵列2中计算(剩余)城市数
    否则,如果(索引_1超出范围)
    从阵列2中计算(剩余)城市数
    否则{
    a=从数组1中获取城市,索引为_1
    b=从数组2中获取城市,索引为_2
    如果(a=b){
    两个阵列中城市的增量数量
    增加两个指数
    }
    否则如果(a
    这应该在阵列大小的线性时间内完成工作

    如果数组未排序,则使用有效的排序算法对其进行排序


    如果数组很小,请不要麻烦,对嵌套循环使用蛮力方法。

    存在性测试最好使用散列对象/字典。Set intersection是您试图执行的操作的术语。你的建议可以完成这项工作,但这不是最有效的方式。