您的位置:首页 > 其它

leetcode题目之两数求和

2017-03-15 11:04 218 查看
题目很简单,返回数组中等于目标的两数的下标。用了两种方法去求解。第一种两层循环,时间复杂度O(n^2) 第二种用了hashmap。时间复杂度O(n).

question:

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].


解题 法1:

public static int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}


法2:

public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}


测试:

public static void main(String[] args)
{
int[] nums={1,0,4,8};
twoSum(nums,9);
int[] num1=twoSum(nums,9);
System.out.println(Arrays.toString(num1));

}


输出:[0,3]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode