LeetCode刷题笔记——Day 1
题目:1.两数之和
题目描述:给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-W9JqtLAJ-1625119686408)(C:\Users\pc\AppData\Roaming\Typora\typora-user-images\image-20210701135908070.png)]
解答法1:暴力解法
双重循环遍历数组,直到找到满足要求的坐标对。
class Solution {
public int[] twoSum(int[] nums, int target) {
int array[] = new int[2];
for(int i=0;i<nums.length-1;i++){
boolean flag = false;
for(int j=i+1;j<nums.length;j++){
if(nums[i] + nums[j]==target){
array[0]=i;
array[1]=j;
flag=true;
break;
}else{
continue;
}
}
if(flag == true){
break;
}
}
return array;
}
}
解答法2:Map集合
利用Map集合中元素唯一性的特征,遍历数组,寻找符合要求的下标组。
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> m = new HashMap<>();
for(int i=0;i<nums.length;i++){
int amother = target-nums[i];
if(m.containsKey(amother)){
return new int[]{m.get(amother),i};
}
m.put(nums[i], i);
}
return new int[0];
}
}