1. 两数之和 - 力扣(LeetCode) (leetcode-cn.com)
题目
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
思路
1、暴力解法,双循环
时间复杂度:O(N2)
空间复杂度:O(1)
自己代码
class Solution {
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[i]+nums[j]==target){
//创建一个数组,有以下方法;定义时可不指定长度,初始化时必须指定长度
//int[] arr = new int[n];
//int[] arr = {1,2,..}
//int[] arr = new int[]{1,2,..}
int[]arr={i,j};
return arr;
}
}
}
//返回一个空数组
return new int[0];
}
}
其他优解
思路
非重,可以无序,元素唯一
既需要目标值,又要确定下标值,不能使用set
用map(哈希表)
改进比较
空间换取时间
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for(int i=0;i<nums.length;i++){
//如果(数组当前值)a(与目标值的差值)b存在于映射表中,这两个就是要找的
int another = target - nums[i]
if(hashtable.containsKey(another)){
return new int[]{i,hashtable.get(another)};
}
//若不存在,就将a添入映射表,键:元素值 值:下标
hashtable.put(nums[i],i);
}
return new int[0];
}
}