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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Thoughts
1. 遍历解法,没有更白痴的解法了。O(N*N)
2. Hashmap,traverse一遍。O(N)
3. Two pointers,前后双指针。O(NlogN)
Solutions
1.
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for(int i = 0; i < nums.length; i++){
for(int j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
2.
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<> ();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(target - nums[i])){
return new int[] { map.get(target - nums[i]), i };
}
map.put(nums[i], i);
}
return new int[2];
}
public int[] twoSum(int[] nums, int target) {
int min = 0;
int max = nums.length - 1;
int[] sorted = new int[nums.length];
System.arraycopy(nums, 0, sorted, 0, nums.length);
Arrays.sort(sorted);
while(min < max){
if(sorted[min] + sorted[max] == target){
break;
}else if(sorted[min] + sorted[max] > target){
max--;
}else{
min++;
}
}
int num1 = sorted[min];
int num2 = sorted[max];
int j = -1;
int k = -1;
for(int i = 0; i < nums.length; i++){
if(nums[i] == num1 && j == -1){
j = i;
}else if(nums[i] == num2 && k == -1){
k = i;
}
}
return new int[] {j,k};
}