您的位置:首页 > 其它

LeetCode Two Sum

2018-02-26 23:20 281 查看
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].给定一组整数nums,返回一个两个数的数组[i,j],可以使得这两个数对应的数组中的值的和nums[i]+nums[j]为target。您可以假设每个输入都有一个解决方案,您不可以使用相同的元素两次。
常用的解法就是两层循环找和是target的两个数,如此的话时间复杂度为O(n​2​​),空间复杂度为
O(1)
O(1)。public 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");
}如果出现给定的数组非常长的话会非常耗时,第二种方法用一层循环,每次循环将元素暂存于Map中,直到第i个元素与Map中某个元素和为target,寻找成功。如此的话时间复杂度为O(n),空间复杂度为O(n)。public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: