讨论/《哈希表》 - 存在重复元素/
《哈希表》 - 存在重复元素
共 5 个回复

简单题

class Solution {
    public boolean containsDuplicate(int[] nums) {
        if(nums.length==1||nums.length==0){
            return false;
        }
        HashSet<Integer> integers = new HashSet<>();
        int originalLength=nums.length;
        for (int i = 0; i <nums.length ; i++) {
            integers.add(nums[i]);
        }
        return integers.size()!=originalLength;
    }
}
1
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            if (!set.add(num)) return true;
        }
        return false;
    }
}
1

感觉这样还行吧。

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            if(set.contains(num)){
                return true;
            }else{
                set.add(num);
            }
        }
        return false;
    }
}
class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return len(set(nums)) < len(nums)

python取巧。

typedef struct {
    int key;
    UT_hash_handle hh;
}HashTable;

HashTable *head = NULL;
/* 清空哈希表 */
void DeleteNode()
{
    HashTable *s = head;
    while (s != NULL) {
        HashTable *tmp = s->hh.next;
        HASH_DEL(head, s);
        free(s);
        s = tmp;
    }
}

bool containsDuplicate(int* nums, int numsSize){
    if (nums == NULL || numsSize == 0) {
        return false;
    }
    head = NULL;
    for (int i = 0; i < numsSize; i++) {
        HashTable *tmp = NULL;
        /* 查找 */
        HASH_FIND_INT(head, nums + i, tmp);
        if (tmp == NULL) {
            tmp = (HashTable *)malloc(sizeof(HashTable));
            tmp->key = *(nums + i);
            /* 添加 */
            HASH_ADD_INT(head, key, tmp);
            continue;
        }
        /* 清空 */
        DeleteNode();
        return true;
    }
    /* 清空 */
    DeleteNode();
    return false;
}