本文是刷力扣题库需要的进车道:
https://leetcode-cn.com/
1.两数相加
1.两次for循环
-
给定一个整数数组 nums 和一个目标值target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
public class Demo10 {
public static int[] twoSum(int[] nums, int target) {
//创建一个数组,用来存数组下标
int[] arr = new int[2];
//第一个for循环
for (int i = 0; i < nums.length - 1; i++) {
//定义temp 使其等于target-第一次for循环的索引所得的元素
int temp = target - nums[i];
//第二次 for 循环
for (int j = i + 1; j < nums.length; j++) {
//使temp等于第二次for循环索引的元素
if (nums[j] == temp) {
//将两次for循环的索引加入arr数组
arr[0] = i;
arr[1] = j;
}
}
}
return arr;//返回arr数组
}
public static void main(String[] args) {
int[] ints = twoSum(new int[]{2, 7, 11, 15}, 9);
System.out.println(Arrays.toString(ints));
}
}
- 首先返回数组下标需要使用一个数组来存储,两次for循环遍历数组索引
- 数组中同一个元素不能使用两遍,那么第一次遍历与第二次遍历索引不能相同 ,所以使第一次for循环的长度少为nums.length 使第二次的for循环开始位置比第一次循环的索引j=i+1;
- 返回arr数组
public class Demo11 {
public static int[] twoSum(int[] nums,int target){
int[] arr =new int[2];
//创建一个哈希表 用元素作为key 下标作为value
HashMap<Integer,Integer> hashMap = new HashMap<>();
//通过第一个for循环 将元素和下标存入哈希表
for (int i=0;i<nums.length;i++){
hashMap.put(nums[i],i);
}
//第二次for循环
for (int j=0;j<nums.length;j++){
//nums[j]为第一个符合的元素,用target-nums[j]作为第二个数的key在哈希表中查找
if (hashMap.containsKey(target-nums[j])&&hashMap.get(target-nums[j])>j){
arr[0]=j;
arr[1]=hashMap.get(target-nums[j]);
}
}
return arr;
}
public static void main(String[] args) {
int[] ints = twoSum(new int[]{2, 7, 11, 15}, 9);
System.out.println(Arrays.toString(ints));
}
}