Given an array of integers, return indices of the both numbers such that they add-to a specific target.
You may assume this each input would has exactly one Solution.
Example:
Given nums = [2, 7, one, 2], target = 9,because nums[0] + nums[1] = + 7 = 9,return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based Indices. Please read the above updated description carefully.
public classSolution { public int[] Twosum (int[] nums,intTarget) { int[] copy =New int[nums.length]; intindex1 = 0; intIndex2 = nums.length-1; intFirst =-1; intSecond =-1; int[] result =New int[2]; System.arraycopy (nums,0, copy, 0, nums.length); Arrays.sort (copy); while(index1 <index2) { if(copy[index1] + copy[index2] = =Target) {result[0] =copy[index1]; result[1] =copy[index2]; break; }Else if(copy[index1] + copy[index2] <Target) {index1++; }Else{index2--; } } for(inti = 0; I < nums.length; i++){ if(result[0] = = nums[i] && first = =-1) { first=i; }Else if(result[1] = = nums[i] && second = =-1) {second=i; }} result[0] =first ; result[1] =second; returnresult; }}
Both Sum Leetcode Java