概述
文章目录
- Leetcode:1. 两数之和
- 题目描述
- 答案
- 方法一
- 方法二
- 方法三
Leetcode:1. 两数之和
题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
答案
方法一
直接暴力枚举,时间复杂度为 O(n2),空间复杂度 O(1)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>(nums.length);
for (int i = 0; i < nums.length; i++) {
Integer ret = map.get(nums[i]);
if (ret != null) {
return new int[] { ret, i };
}
map.put(target - nums[i], i);
}
return new int[] { -1, -1 };
}
}
方法二
将数组先放入一个Map中,然后遍历一遍数组,找map中有没有对应的target - nums[i]
的值. 时间复杂度O(n) 空间复杂度O(n)
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int temp = target - nums[i];
if (map.containsKey(temp) && map.get(temp) != i) {
return new int[] { i, map.get(temp) };
}
}
throw new RuntimeException("no num");
}
}
更极致的解法
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map= new HashMap();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(target - nums[i])) {
return new int []{map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
return new int[]{};
}
}
方法三
class Solution {
public int[] twoSum(int[] nums, int target) {
int max = 2047;
int[] res = new int[max + 1];
for (int i = 0; i < nums.length; i++) {
int index = (target - nums[i]) & max;
if(res[index] != 0){
return new int[]{res[index] - 1, i};
}
res[nums[i] & max] = i + 1;
}
return new int[2];
}
}
最后
以上就是想人陪煎饼为你收集整理的Leetcode:1. 两数之和Leetcode:1. 两数之和的全部内容,希望文章能够帮你解决Leetcode:1. 两数之和Leetcode:1. 两数之和所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复