[LeetCode]Contains Duplicate

原题链接

question

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.

my answer

使用图的邻接矩阵的思想

//解题思路:使用图的邻接矩阵存储模型
#define N 100 //size of hash table

typedef struct node{
    int val;
    struct node* next;
}node;

typedef struct myHash{
    node* head;
    node* tail;
}myHash;

bool containsDuplicate(int* nums, int numsSize){
    myHash* hashTable= (myHash*)malloc(100*sizeof(myHash));

    // initialize
    for (int i=0; i<N; ++i)
    {
        hashTable[i].head = hashTable[i].tail = NULL;
    }

    int tmp=0;

    for (int i=0; i<numsSize; ++i)
    {
        tmp = ((int)abs(nums[i]))%N;

        if (!hashTable[tmp].head)//hash表中当前元素所指的位置为空
        {
            //printf("a %d %d %d\n",nums[i],tmp, i);
            node* newNode = (node*)malloc(sizeof(node));
            newNode->val = nums[i];
            newNode->next = NULL;
            hashTable[tmp].head = newNode;
            hashTable[tmp].tail = newNode;
        }else{
            //printf("b %d %d %d \n",nums[i],tmp, i);
            node* ptrNode = hashTable[tmp].head;
            //遍历检查当前链表
            while(ptrNode){
                if(ptrNode->val == nums[i])
                    return true;
                ptrNode = ptrNode->next;
            }
            // 尾插法
            ptrNode = (node*)malloc(sizeof(node));
            ptrNode->val = nums[i];
            ptrNode->next = hashTable[tmp].head;
            hashTable[tmp].head = ptrNode;
        }
    }

    return false;
}

others’ answer

使用bitmap的思想

#include <stdlib.h>

#define BIT_PER_WORD 32
#define SHIFT 5 //2^5==32
#define MARK 0x1f
#define MAX_NUM 10000000

/**
 * 算法思路:使用bitmap结构
 * (i & MARK) <-> i mod MARK
*/

void clear(int* arr, int i){//将元素i所对应的位置零
    arr[i>>SHIFT] &= ~(1 << (i & MARK));
}

int test(int* arr, int i){//是否已经被填充
    return arr[i>>SHIFT] & (1 << (i & MARK));
}

void set(int* arr, int i){//将元素i所在的位置1
    arr[i>>SHIFT] |= (1 << (i & MARK));
}

int containsDuplicate2(int* nums, int numsSize){
    int* arr = (int*)malloc((MAX_NUM/BIT_PER_WORD+1)*sizeof(int));

    for(int i=0; i<numsSize; ++i){
        clear(arr, nums[i]);
    }

    for(int i=0; i<numsSize; ++i){
        if(test(arr, nums[i]))
            return true;
        set(arr,  nums[i]);
    }

    return false;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值