1、题目来源:点击打开链接
2、题目:
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.
3、思路1:和上一题类似的做法,不过数组不能像String类型那样count[c-'a']来进行计数:
A、从第2个数开始遍历,每个数与前面的任一个数比较,若出现相同的数,则返回true;
B、遍历完成后还未出现相同的数返回false;
C、暴力解法时间超限,卒:
public class Solution {
public boolean containsDuplicate(int[] nums) {
if(nums.length==0)
return false;
int []count=new int[nums.length];
int x=nums[0],i,j;
for(i=1;i<nums.length;i++){
for(j=0;j<i;j++)
if(nums[i]==nums[j])
return true;
}
return false;
}
}4、思路2:先排序,然后遍历一次,使用Arrays.sort(nums)进行排序,通过:
public class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
int i;
for(i=0;i<nums.length-1;i++){
if(nums[i]==nums[i+1])
return true;
}
return false;
}
}
本文介绍两种检测数组中是否存在重复元素的方法:暴力解法与排序后遍历检查。暴力解法直接对比所有元素对,而排序后遍历法则先对数组进行排序,再逐个检查相邻元素是否相同。

815

被折叠的 条评论
为什么被折叠?



