問題:給定一個整型數組,找出其中的兩個數使其和爲某個指定的值,並返回這兩個數的下標。假設數組元素的值各不相同,則要求時間複雜度爲O(n), n爲數組的長度。
思路:掃描一遍數組,把鍵值<value, index>存入哈希表,再次掃描檢查target與當前的差值是否在哈希表中。
java實現:
int[] twoSum(int[] A,int target){
int[] res={-1,-1};
if(A==null||A.length<2)
return res;
HashMap<Integer,Integer> ihm=new HashMap<Integer,Integer>();
for(int i=0;i<A.length;i++){
ihm.put(A[i],i);
}
for(int i=0;i<A.length;i++){
if(ihm.containsKey(target-A[i])&&target!=2*A[i]){
res[0]=i;
res[1]=ihm.get(target-A[i]);
break;
}
}
return res;
}