难度:easy
1、题目描述:
给定一个整数数组,判断是否存在重复元素。
如果存在一值在数组中出现至少两次,函数返回
true
。如果数组中每个元素都不相同,则返回false
。
2、思路分析:
一、我自己想到的方法是采用俩个指针i和j,分别对数组中的数据进行逐个比较。相等返回true,反之返回false。时间复杂度为:
代码:
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
if (nums[i] == nums[j]) {
return true;
}
}
}
return false;
二、第二种方法:将数组进行排序【使用Arrays工具类】,比较相邻的俩个元素,相等返回true,时间复杂度:
代码:
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i + 1]) {
return true;
}
}
return false;
三、第三种方法:使用Arrays工具类里面的stream方法,对数组的元素进行去重统计。
代码:
//第三种做法:对数组进行去重统计,统计的数比数组长度小说明有重复的数据
return Arrays.stream(nums).distinct().count() < nums.length;