close

題目

Given an array of intergers, 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.

想法

一開始覺得可以檢查這個數字,在先前有沒有出現過,但是複雜度過高。

若可以先排序,就可以看到相同數字會相鄰出現。

code

int cmp(const void *a, const void *b) {
    int c = *(int*)a;
    int d = *(int*)b;
    if (c > d)
        return 1;
    else
        return 0;
}

bool containsDuplicate(int* nums, int numsSize) {
    qsort(nums, numsSize, sizeof(int), cmp);
    int i = 0;
    int temp = nums[0];
    for (i=1; i<numsSize; i++) {
        if (temp == nums[i]) {
            return 1;
        }
        temp = nums[i];
    }
    
    return 0;
    
}

 

 

arrow
arrow
    文章標籤
    LeetCode C
    全站熱搜

    Davis 發表在 痞客邦 留言(0) 人氣()