标签:The 数组 leetcode 没有 说明 cti 17. should element
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
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
用set,如果没有遇到重复的,也就是如果某个元素添加set失败,则说明有重复的。
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new TreeSet<Integer>();
for(int i : nums) {
if(!set.add(i))
return true;
}
return false;
}
}
先给数组排序,然后遍历一遍比较相邻元素是否有相等的。时间复杂度取决于排序算法的复杂度。
class Solution {
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;
}
}
[leetcode]217.Contains Duplicate
标签:The 数组 leetcode 没有 说明 cti 17. should element
原文地址:https://www.cnblogs.com/shinjia/p/9785354.html