LeetCode - 217. Contains Duplicate

LeetCode217

題目: 217. Contains Duplicate

給一數字陣列,找出裡面是否有重複的數字。

解題思路

思路一: iterate陣列nums,並把看過的num存在set中;如果num已經在set中,則返回True;
    否則iterate結束(代表沒有找到有重複的num)則返回False。

思路二: 排序陣列nums後,從第二個(index = 1)開始iterate整個陣列,並檢查前一個num與當前num是否相同,相同則重複;
    否則iterate結束(代表沒有找到有重複的num)則返回False。

Code

Java:

Runtime 5 ms(96.38%), Memory 50.6 MB(96.43%)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    public boolean containsDuplicate(int[] nums) {
        HashSet<Integer> viewed = new HashSet<Integer>();
        for(int i=0; i<nums.length; i++){
            if(!viewed.add(nums[i])){
                return true;
            }
        }
        return false;
    }
}

Python3:

Runtime 464 ms(85.88%), Memory 25.9 MB(91.76%)

1
2
3
4
5
6
7
8
9
class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        viewed = set()
        for i in range(len(nums)):
            if nums[i] in viewed:
                return True
            else:
                viewed.add(nums[i])
        return False

C#:

Runtime 199 ms(66.51%), Memory 52.2 MB(36.17%)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class Solution {
    public bool ContainsDuplicate(int[] nums) {
        HashSet<int> viewed = new HashSet<int>();
        for(int i=0; i<nums.Length; i++){
            if(!viewed.Add(nums[i])){
                return true;
            }
        }
        return false;
    }
}

Golang:

Runtime 65 ms(97.15%), Memory 8.9 MB(55.31%)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
type void struct{}
var empty void

func containsDuplicate(nums []int) bool {
    viewed := make(map[int]void);
    for _, num := range nums {
        if _, ok := viewed[num]; ok {
            return true;
        }else{
            viewed[num] = empty;
        }
    }
    return false;
}

C++:

Runtime 112 ms(68.51%), Memory 51.5 MB(52.15%)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_set<int> viewed;
        for(int i=0; i<nums.size(); i++){
            if (viewed.count(nums[i])){
                return true;
            }else{
                viewed.insert(nums[i]);
            }
        }
        return false;
    }
};

C:

Runtime 125 ms(73.38%), Memory 12.6 MB(90.14%)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
int compare(const int *a, const int *b){
    return *a - *b;
}

bool containsDuplicate(int* nums, int numsSize){
    qsort(nums, numsSize, sizeof(int), compare);

    for(int i=1; i<numsSize; i++){
        if (nums[i - 1] == nums[i]){
            return true;
        }
    }
    return false;
}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus