Because nums[0] + nums[1] = 2 + 7 = 9,
(leetcode)1. 查找數組中兩個數之和爲給定值Two Sum---Java
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
給定一個整數數組,返回兩個數字的索引,使得它們相加到一個特定的目標。
您可以假設每個輸入都有一個解決方案。
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
我的解法:思路是把數組裝進arraylist列表裏面,然後做一次循環,每次用列表裏面的第i個數和後面的第n-i個數做判斷。這樣做沒有最快的答案好,但是思路是一樣的,原因在於,
我是先一次性全部放進去,這裏花時間。然後,每次比較,我又取了全部list的子列表arraylist,這裏也花時間。
public
int[] twoSum(int[]
nums,
int
target) {
List<Integer>s
=
new
ArrayList<Integer>();
int
len
=
nums.length;
for(int
i=0;i<len;i++){
s.add(nums[i]);
}
//Collections.sort(s);
for(int
i=0;i<len-1;i++){
// System.out.println(i+" i " +
len+ "
len");
// System.out.println(s.subList(i+1,
len)+" "+(target-nums[i]));
if(s.subList(i+1,
len).contains(target-nums[i])){
int[]res
=
new
int[2];
res[0]
=
i;
res[1]
= 1+i+s.subList(i+1,
len).indexOf(target-nums[i]);
return
res;
}
}
return
null;
}
標準算法:
public
int[] twoSum2(int[]
numbers,
int
target) {
int[]
result
=
new
int[2];
Map<Integer, Integer>
map
=
new
HashMap<Integer, Integer>();
for
(int
i
= 0;
i
<
numbers.length;
i++) {
if
(map.containsKey(target
-
numbers[i]))
{
result[1] =
i
;
result[0] =
map.get(target
-
numbers[i]);
return
result;
}
map.put(numbers[i],
i
);
}
return
result;
}
放在hashmap裏面,這樣,在找到值的時候,去找對應的鍵就很快,比arraylist中的indexof要快,
另外,採用倒敘的方式,每次比較,比不到就加一個,加一個比截取一大段複雜度要低很多。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.