Description:
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
注意事项
You may assume that each input would have exactly one solution.
Explanation:
Given nums = [2, 7, 11, 15]
, target = 9
return [1, 2]
Solution:
Set up two pointers,one points to the start; the other go through the rest of the array.Record the sum of the numbers that pointers point to and compare it to the target.If equal, add the pointers to the result array. Remember to add 1 to the pointers.
public class Solution {
/*
* @param nums an array of Integer
* @param target = nums[index1] + nums[index2]
* @return [index1 + 1, index2 + 1] (index1 < index2)
*/
public int[] twoSum(int[] nums, int target) {
// write your code here
int[] result = new int[2];
for(int i = 0;i<nums.length-1;i++){
int temp = target - nums[i];
for(int j = i + 1;j<nums.length;j++){
if(temp == nums[j]){
result[0] = i+1;
result[1] = j+1;
return result;
}
}
}
return result;
}
}