leetcode初級算法題-存在重複

題目:

給定一個整數數組,判斷是否存在重複元素。

如果任何值在數組中出現至少兩次,函數返回 true。如果數組中每個元素都不相同,則返回 false。

示例 1:

輸入: [1,2,3,1]
輸出: true

示例 2:

輸入: [1,2,3,4]
輸出: false

示例 3:

輸入: [1,1,1,3,3,4,3,2,4,2]
輸出: true

解題思路(C):

   首先想到的是兩層for循環,以此判斷兩兩是否相等,但提交時,超出時間限制

代碼:

bool containsDuplicate(int* nums, int numsSize) {
    int i, j;
    int repeat = 0;
    for(i=0;i<numsSize;i++){
        for(j=0;j<numsSize;j++){
            if((nums[i]==nums[j])&&(i!=j))
                repeat = 1;
        }
    }
    if(repeat)
        return true;
    else
        return false;
}

改進一下:去掉重複比較

    第0個元素和後面的1到n個元素比較

    第1個元素和後面的2到n個元素比較

代碼:

bool containsDuplicate(int* nums, int numsSize) {
    int i, j;
    int repeat = 0;
    for(i=0;i<numsSize;i++){
        for(j=i+1;j<numsSize;j++){
            if(nums[i]==nums[j])
                repeat = 1;
        }
    }
    if(repeat)
        return true;
    else
        return false;
}

解題思路(python):

python的counter,統計值出現的次數

例子:

import collections

test = collectionsCounter("abcdefgabc")

print(test)

#輸出每個字符出現的次數

代碼:

import collections
class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        num_result = collections.Counter(nums)
        for value in num_result.values():
            if value >= 2:
                return True
        return False

參考:

1、leetcode刷題--基礎數組--判斷存在重複(C)    https://blog.csdn.net/qq_28266311/article/details/82989456

2、python的collection系列-counter  https://www.cnblogs.com/repo/p/5422041.html

3、Leetcode——存在重複元素——python3   https://blog.csdn.net/lzw369639/article/details/82814056

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章