Two Sum両数の和
1271 ワード
LettCodeのブラシ問題の旅を始めて、堅持します!
生涯TwoSumを知らず、LeetCodeを尽くしてもむだだ.
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:
Javaコード実装:
生涯TwoSumを知らず、LeetCodeを尽くしてもむだだ.
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].
Javaコード実装:
public static int[] TwoSum(int[] arr,int target){
HashMap hashMap=new HashMap();
int[] result=new int[2];
for(int i=0;i
public int[] TwoSum(int[] nums, int target) {
HashMap m = new HashMap();
int[] res = new int[2];
for (int i = 0; i < nums.length; ++i) {
if (m.containsKey(target - nums[i])) {
res[0] = i;
res[1] = m.get(target - nums[i]);
break;
}
m.put(nums[i], i);
}
return res;
}