LeetCode Array 167 Two Sum
II - Input array is sorted
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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解读:给定一个升序数组,和一个目标值。求数组中哪两个元素相加会得到目标值。输出相应的索引+1.
分析:和Two Sum的思路一样,使用Map来存储数组元素,key为数组元素的值,value为数组元素的索引+1。(要求输出非零值)
public int[] twoSum(int[] numbers, int target) {
Logger.getGlobal().info("获得数组"+Arrays.toString(numbers));
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
map.put(numbers[i], i + 1);
}
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {
return new int[]{i + 1, map.get(target - numbers[i])};
}
}
throw new RuntimeException("无解!");
}
I Two Sum 1
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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
分析:使用Map来存放数组元素,Map中containsKey函数查找target-nums[i]是否存在。
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> m=new HashMap<>();
for (int i = 0; i <nums.length; i++) {
m.put(nums[i],i);
}
int i=0,j=0;
for (i = 0; i <nums.length ; i++) {
int temp=target-nums[i];
if(m.containsKey(temp)&&i!=m.get(temp))
{
// j=m.get(temp);
//break;
return new int[]{i,m.get(temp)};
}
}
throw new IllegalArgumentException("no two sum souletiomn");
}