leetcode [#217]

目录

题目

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.


解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {
public boolean containsDuplicate(int[] nums) {
int N = nums.length;
if(nums == null || N == 0) return false;

Arrays.sort(nums);
boolean result = false;
for(int k = 0; k < N-1; k++){
if(nums[k] - nums[k+1] == 0){
result = true;
}
}
return result;
}
}

注意事项

  1. 将数组排序,遍历,如果有相邻两项相同,说明有相同元素。