【问题标题】:my solution to 2-sum is slow?我对 2-sum 的解决方案很慢?
【发布时间】:2013-04-11 01:19:47
【问题描述】:

我正在研究 2-sum 问题,我认为我的解决方案非常有效,但是在我运行它之后,程序显然花费了太长时间。这是我的代码:

  public int[] twoSum(int[] numbers, int target) {
        int [] original = new int[numbers.length];
        for(int i=0; i<numbers.length; i++){
            original[i] = numbers[i];
        }
        Arrays.sort(numbers);
        int [] returnArray = new int[2];
        int left = 0;
        int right = numbers.length-1;
        int found1 = 0, found2 = 0;
        int index1 = 1, index2 = numbers.length-1;
        for (;left<right;){
            if(numbers[left] + numbers[right] == target){
                found1 = numbers[left];
                found2 = numbers[right];
                break;
            }
            else if(numbers[left] + numbers[right] < target){
                left++;
            }
            else{
                right--;
            }
        }
        for(;index1<index2;){
            if(original[index1] == found1){
                returnArray[0] = index1+1;
            }
            else{
                index1 ++;
            }
            if(original[index2] == found2){
                returnArray[1] = index2+1;
            }
            else{
                index2 --;
            }

        }
        return returnArray;
    }

问题说明

您可以假设每个输入都只有一个解。函数 twoSum 应该返回两个数字的索引,以便它们相加到目标,其中 index1 必须小于 index2。请注意,您返回的答案(index1 和 index2)不是从零开始的。

我的想法是先对数组进行排序,然后找到这两个元素,然后是两个索引。而且我认为有必要先存储原始数组,因为排序会改变数组。我的解决方案的哪一部分很慢?

附:我不经常使用Java,欢迎指出我的错误。

谢谢。

【问题讨论】:

  • 我认为 2-sum 问题的重点是使用哈希并不断查找。
  • 按照SGM1链接中的解决方案
  • @Keith 是的,这是一种常见的解决方案。但首先对数组进行排序是另一回事。
  • @Patashu 返回找到的元素的这两个索引的要求有什么不同吗?

标签: java algorithm performance


【解决方案1】:

你在这里有两张通行证。一个是查找数字,另一个是记住原始索引。

如果你一开始就保留了索引,那么你就避免了第二遍。

从一个包含索引的数组开始,即 { 1,2,3,4, ...},然后使用非默认比较器对其进行排序:

sort(T[] a, Comparator<? super T> c)

让该比较器使用原始数组中的值对索引进行排序。

然后在索引上运行你的二和,你已经有了索引值。

【讨论】:

  • Have that comparitor order the index using the values in the original array 我不太明白用原始部分对数组进行排序,你能举个例子吗?
  • @Gnijuohz 他的意思是将原始索引视为卫星数据,并将它们与原始数组元素一起移动作为排序的一部分。为此,您可以根据原始数组的值对索引数组进行排序。详情请查看stackoverflow.com/questions/5898690/…
猜你喜欢
  • 2015-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-30
  • 2021-10-26
  • 2014-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多