本文共 1122 字,大约阅读时间需要 3 分钟。
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
查询类的题目首先想到的是hashset和hashmap
class Solution { public boolean containsDuplicate(int[] nums) { Setset = new HashSet<>(); for(int i = 0; i < nums.length; i++){ if(set.contains(nums[i])) return true; set.add(nums[i]); } return false; }}
因为只判断是否含有,不考虑index,可以用双指针
性能比上一个方法更好class Solution { public boolean containsDuplicate(int[] nums) { if(nums.length < 2) return false; Arrays.sort(nums); for(int i = 0, j = 1; j < nums.length; i++, j++){ if(nums[i] == nums[j]) return true; } return false; }}
j这个变量完全可以省去,边界条件可以放在for循环中判断
public boolean containsDuplicate(int[] nums) { Arrays.sort(nums); for (int i = 0; i < nums.length - 1; ++i) { if (nums[i] == nums[i + 1]) return true; } return false;}
转载地址:http://ubqvb.baihongyu.com/