Skip to content

[LeetCode]136. 只出现一次的数字 #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Animenzzzz opened this issue Aug 1, 2019 · 0 comments
Open

[LeetCode]136. 只出现一次的数字 #21

Animenzzzz opened this issue Aug 1, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

说明:

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:

输入: [2,2,1]
输出: 1

示例 2:

输入: [4,1,2,1,2]
输出: 4

解题思路:第一想法,使用哈希表,用一个权重值

C解题:

struct HashMap {
    int value;
    int index;
    int weight;
    UT_hash_handle hh;
};
int singleNumber(int* nums, int numsSize){
    struct HashMap *hashmap = NULL,*hashtmp=NULL;
    for (int i = 0; i < numsSize; i++)
    {
        HASH_FIND_INT(hashmap,&nums[i],hashtmp);
        if (hashtmp)
        {
            hashtmp->weight--;
            continue;
        }
        hashtmp = (struct HashMap *)malloc(sizeof(struct HashMap));
        hashtmp->value = nums[i];
        hashtmp->index = i;
        hashtmp->weight = 2;
        HASH_ADD_INT(hashmap,value,hashtmp);
    }
    for (int i = 0; i < numsSize; i++)
    {
        HASH_FIND_INT(hashmap,&nums[i],hashtmp);
        if (hashtmp->weight == 2)
        {
            return nums[hashtmp->index];
        }
    }
    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant