Contains Duplicate [leetcode] 判断数组中是否有重复的元素

来源:互联网 发布:三菱触摸屏软件 编辑:程序博客网 时间:2024/06/09 07:54

Contains Duplicate

题意: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.
理解:给定一个数组,判断数组中是否有重复的元素,若存在相同的元素就返回true,否则返回false。
解决思路:
1.朴素解法,O(n^2),用for循环嵌套比较,但时间复杂度太高,不能通过。
2.先排序(快速排序),时间复杂度O(nlogn),能通过编译。
3.可能还存在复杂度更低的解法,暂时没想到。
对于快速排序,空间消耗O(1),但原始数组次序会被打乱。实现C语言代码如下:

int Partition(int *nums,int low, int high){//一份为二,前半部分小于pivotkey,后半部分大于pivotkey    int temp, pivotkey;    pivotkey = nums[low];    temp = pivotkey;    while(low < high){        while(low < high && nums[high] >= pivotkey){            high--;        }        nums[low] = nums[high];        while(low < high && nums[low] <= pivotkey){            low++;        }        nums[high] = nums[low];    }    nums[low] = temp;    return low;}void QSort1(int *nums,int low, int high){//快速排序算法,耗时在O(nlogn),还是很严重,还怠于优化    int pivot;    while(low < high){        pivot = Partition(nums,low,high);        QSort1(nums,low,pivot-1);        low = pivot+1;    }}bool containsDuplicate(int* nums, int numsSize) {    int i,j;    if(nums == NULL || numsSize <= 1)return false;    QSort1(nums,0,numsSize-1);    for(i = 0; i < numsSize-1; i++){        if(nums[i] == nums[i+1]){            return 1;        }    }    return false;}
0 0
原创粉丝点击