给你一个整数数组 nums
。如果任一值在数组中出现 至少两次 ,返回 true
;如果数组中每个元素互不相同,返回 false
。
示例 1:
输入:nums = [1,2,3,1] 输出:true
示例 2:
输入:nums = [1,2,3,4] 输出:false
示例 3:
输入:nums = [1,1,1,3,3,4,3,2,4,2] 输出:true
bool函数默认为判断true与false的函数。
看到这几个题觉得直接内外双for循环比较就行了,写了一下运行不成功,发现别的作者有把结果先用n=1标记,再用if语句返回true与false,不理解但是改了一下就能运行了。
bool containsDuplicate(int* nums, int numsSize){
int n = 0;
for(int i = 0;i< numsSize -1;i++){
for(int p = i + 1;p<= numsSize -1;p++) {
if (nums[i] == nums[p]) {
n = 1;
}
}
if(n == 1) {
return true;
}
else {
return false;
}
}
}
美中不足的是,超时了。
另一思路说,先排序,再遍历比较相邻的数,有相同就true。这个代码还是写了个函数用来排序(据说是快速排序),我还是不太会。
void swap(int *x,int *y){ int temp; temp = *x; *x = *y; *y = temp; }
//快排不要简单的选择nums[low]作为枢纽值,不然遇到顺序的数组时间复杂度将到n2
int partition(int *nums,int low,int high){
int pivot;
int mid = (low+high)/2;
swap(&nums[mid],&nums[low]);
pivot = nums[low];
while(low<high){
while(low<high&&nums[high]>=pivot){
high--;
nums[low] = nums[high];
}
while(low<high&&nums[low]<=pivot){
low++;
nums[high] = nums[low];
}
}
nums[low] = pivot;
return low;
}
void quick_sort(int *nums,int low,int high){
if(low<high){
int pivot = partition(nums,low,high);
quick_sort(nums,low,pivot-1);
quick_sort(nums,pivot+1,high);
}
}
bool containsDuplicate(int* nums, int numsSize){
if(numsSize==0)
return false;
int flag,i;
quick_sort(nums,0,numsSize-1);
for(i=0;i<numsSize-1;i++){
if(nums[i]==nums[i+1])
return true;
}
return false;
}
——————————————————————————————————————————
class Solution {
public boolean containsDuplicate(int[] nums) {
//创建set集合(set集合的元素不能有重复(性质))
Set<Integer> integerSet = new HashSet<>();
//遍历数组,一个一个添加到set数组
for (int num : nums) {
//如果不能添加,说明数组中已经有此数
if(!integerSet.add(num)){
return true;
}
}
return false;
}
}
提交OK,真厉害👍