leetcode 217 Contains duplicate
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.
思路:
这道题是在数组中判断是否有重复值,如果每个值都没重复,返回false,否则返回true
采用一个对象存储数组,遍历数组,如果obj有这个属性就存入1,否则就是有重复返回true,遍历完了还没有重复就是独一无二,最后返回false
var containsDuplicate = function(nums) {
var obj={};
for(var i=0;i<nums.length;i++){
if(! obj[nums[i]]){
obj[nums[i]]=1;
}else{
return true;
}
}
return false;
};
leetcode 219. Contains Duplicate II
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.
思路:
这道题是上一题目的拓展,判断是否找到两个重复的值,且他们的小标index的差值要小于k
!注意:
1、赋值的时候从1开始,从0开始的话下一次进入判断的时候是0,是不存在的
2、如果找到重复的但差值大于k了之后也要把value的值进行更新,以找到后边的差值小于k的
var containsNearbyDuplicate = function(nums, k) {
var obj={};
for(var i=0;i<nums.length;i++){
if(! obj[nums[i]]){
obj[nums[i]]=i+1;
}else{
if((i-obj[nums[i]]+1)<=k){
return true;
}
obj[nums[i]]=i+1;
}
}
return false;
};
leetcode 220 Contains Duplicate III
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
思路:这道题目和前边两道关系不大,没有涉及重复值的问题。
判断数组中是否存在两个数字的坐标差不能大于k,值差不能大于t。