1 . Two Sum
Easy
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].
10ms:
public int[] twoSum(int[] nums, int target) {
int[] re = {0,0};
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
re[1] = i;
re[0] = map.get(target-nums[i]);
}else{
map.put(nums[i], i);
}
}
return re;
}
57ms:
public int[] twoSum(int[] nums, int target) {
int[] re = {0,0};
for(int i=0;i<nums.length;i++){
int a = nums[i];
for(int j=i+1;j<nums.length;j++){
if(a+nums[j]==target){
re[0] = i;
re[1] = j;
}
}
}
return re;
}
167 . Two Sum II - Input array is sorted
Medium
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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
1ms:
public int[] twoSum(int[] numbers, int target) {
int [] res = new int[2];
int low = 0,high =numbers.length-1;
while(numbers[low]+numbers[high]!=target){
if(numbers[low]+numbers[high]<target)
low++;
else
high--;
}
res[0] = low+1; res[1] = high+1;
return res;
}