1. 程式人生 > >Contains Duplicate [leetcode] 判斷陣列中是否有重複的元素

Contains Duplicate [leetcode] 判斷陣列中是否有重複的元素

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; }