一 存在重复元素
关键代码:
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for (int n : nums) {
if (!set.add(n)) {
return true;
}
}
return false;
}
}
思路:可以利用容器Set元素唯一 的特点,将nums[]中的元素加入,如果不可以添加说明该元素在数组中个数>=2 返回false,否则返回true
二 两数之和
关键代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
//指定数组长度为2
int arr[]=new int[2];
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(nums[i])){
arr[0]=map.get(nums[i]);
arr[1]=i;
}
map.put(target-nums[i],i);
}
return arr;
}
}
思路:先使用for循环遍历数组 nums,判断map中是否存在 target-nums[i] 的 key 值,
如果存在则找到了两个值,如果不存在则将当前的 (nums[i],i) 存入 map 中,继续遍历直到找到为止