要求:
给定一个整数组nums和一个目标值target,请你在该数组中找出和为目标值的那两个整数,
并返回他们的数组下标。
假设每种输入只会对应一个答案,但是不能重复利用这个数组中同样的元素
1枚举:
枚举在数据中所有的不同的两个下标的组合
逐个检查他们所对应的数的和是否等于target
- 时间复杂度:O(n²),这里n为数组长度
- 空间复杂度:O(1),只用到常数个临时变量
public int[] twoSum(int[] nums,int target){
int[] array=new int[2];//也可以不定义返回匿名数组
for (int i = 0; i <nums.length ; i++) {
for(int j=i+1;j<nums.length-i;j++){
if (nums[i]+nums[j]==target){
array[0]=i;
array[1]=j;
}
}
}
/*[0]+[1]=2+5 [0]+[2]=2+7=9 [0]+[3]=2+6
[1]+[2]=5+7 [1]+[3]=5+6
[2]+[3]=7+6
*
* */
return array;
}
1.2 返回匿名数组,但要创建抛出异常对象
public static int[] twoSums(int[] m,int n){
for (int i = 0; i < m.length; i++) {
for (int j=i+1;j<m.length;j++){
if (m[i]+m[j]==n){
return new int[]{i,j};
}
}
}
throw new IllegalArgumentException("未找到");
}
测试
public static void main(String[] args) {
int[] a={2,5,7,6};
int[] arr=twoSums(a,9);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
2.HashMap
空间换取时间,少一层for循环
查表
- 时间复杂度:O(n),n为数组长度
- 空间复杂度:O(n),哈希表中最多需要存n-1个键值对
循环查询值,若不存在map.get( )==null;则存入map中
public static int[] tsh(int[] m,int n){
//hashmap 初始化时,尽量指定初始值大小,虽然hashmap是可以自动扩容的,但是不指定会频繁消耗资源
HashMap<Integer, Integer> map = new HashMap<>(m.length-1);
int[] res=new int[2];
for (int i = 0; i < m.length; i++) {//i=0; i=1; i=2;
int dif=n-m[i]; //dif=7; dif=4; dif=2;
if (map.get(dif)!=null){ //=null; =null; !=null; map.get(key)=0
res[0]=map.get(dif); // res[0]=0;
res[1]=i; // res[1]=2;
return res; // res={0,2};结束
}
map.put(m[i],i); //put(2,0); put(5,1)
}
return res;
}