记录LeetCode岁月(217. Contains Duplicate)

要求

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Examples

Input: nums = [1,2,3,1]
Output: true
Input: nums = [1,2,3,4]
Output: false
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

输入值范围

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109

解答

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Arrays.sort(nums);
        for(int i = 1;i

先排序,如果一个数字出现了n次,那说明至少出现两次,则一定在遍历时遍历到后一个数等于前一个数,直接返回true。如果没有遍历到此情况,则说明没有重复,返回false。

你可能感兴趣的:(记录LeetCode岁月(217. Contains Duplicate))