题目217:
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the
array, and it should return false if every element is distinct.
分析:
解法1:
class Solution {
public boolean containsDuplicate(int[] nums) {
//给定数组,判定其中是否包含重复数据,若存在返回true,否则false
//肯定有坑
if(nums.length==0||nums==null)return false;
Arrays.sort(nums);
for(int i=0;i<nums.length-1;i++){
if(nums[i]==nums[i+1]){
return true;
}
}
return false;
}
}
解法2(推荐):
class Solution {
public boolean containsDuplicate(int[] nums) {
//给定数组,判定其中是否包含重复数据,若存在返回true,否则false
//解法2:使用Set集合实现
//使用set集合实现
//set集合由HashSet和TreeSet继承实现
//set集合不同于List集合,set(存储和取出顺序不一致)唯一
// List(存取和取出顺序一致)可重复
Set<Integer> set = new HashSet<>();
for(int i=0;i<nums.length;i++){
if(!set.add(nums[i])){
//add方法如果包含,返回true
return true;
}
}
return false;
}
}
题目219:
Given an array of integers and an integer k,
find out whether there are two distinct indices i and j in
the array such that nums[i] = nums[j] and
the absolute difference
between i and j is
at most k.
分析:
解法1:
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
//给定数组和k,找出是否存在两个相同数之间的下标差值不能大于k
HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(hm.containsKey(nums[i])){
//包含相同值
int oldIndex=hm.get(nums[i]);
if(i-oldIndex<=k){
return true;
}else{
//防止出现,后面有更小的距离,所以更新为最新下标
hm.put(nums[i],i);
}
}else{
//不包含相同值,直接存
hm.put(nums[i],i);
}
}
return false;
}
}
解法2(推荐):
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
//给定数组和k,找出是否存在两个相同数之间的下标差值不能大于k
//思路:从当前下标开始,判定给定长度内,从尾部往头部遍历
if(k>=35000)return false;
for(int i=0;i<nums.length;i++){
//取尾部,跟数组长度比较,防止头尾有相同
for(int j=Math.min(nums.length-1,i+k);j>i;j--){
if(nums[i]==nums[j])return true;
}
}
return false;
}
}