“来啦来啦!!!”
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.
Example 1:Input: [1,2,3,1]
Output: true
Example 2:Input: [1,2,3,4]
Output: false
关公面前耍大刀
这真的是一道easy的题目,我的想法是想把数组排序,然后比较相邻的元素是否相等即可!但是我还是厚颜无耻的调用了java自带的排序函数。
class Solution {
public boolean containsDuplicate(int[] nums) {
java.util.Arrays.sort(nums);
for(int i=0;i<nums.length-1;i++){
if(nums[i] == nums[i+1])
return true;
continue;
}
return false;
}
}
关公耍大刀
太困了,明天补上
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.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
关公面前耍大刀
我只想到暴力破解法。
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
int n=nums.length;
for(int i=0;i<n;i++){
for(int j=1;j<=k;j++){
if((i+j)>n-1) break;
if(nums[i] == nums[i+j])
return true;
continue;
}
}
return false;
}
}
时间性能差到垫底。
关公耍大刀
主要思想是利用HashSet集合中不能重复添加元素的特点,但是因为比较的数组元素必须在间隔k之内,所以当i>k之后,必须删除掉最前面的元素,以免影响结果。
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nums.length; i++){
if(i > k) set.remove(nums[i-k-1]);
if(!set.add(nums[i])) return true;
}
return false;
}
这貌似不是最好的解法,以后在回来想(抄)。
HashMap 和 HashSet的比较?