当前位置: 代码迷 >> 综合 >> 从数组中找两元素,其和等于给定的数
  详细解决方案

从数组中找两元素,其和等于给定的数

热度:66   发布时间:2024-01-20 03:11:52.0

最直观的方法是两次扫描数组,判断target-array[i]是否存在数组中。这样做的时间复杂度是O(n^2)。

如何保存之前的处理结果?可以使用hash table "target - array[i]是否存在数组中。

vector<int> addsToTarget(vector<int>& numbers,int target)
{unordered_map<int,int> numToIndex;vector<int> vi(2);for(auto it = numbers.begin(); it != numbers.end(); it++){if(numToIndex.count(target - *it)){vi[0] = numToIndex[target - *it] + 1;vi[1] = (int)(it - numbers.begin()) + 1;return vi;}numToIndex[*it] = (int)(it - numbers.begin());}
}

 

  相关解决方案