leetcode_260. 只出现一次的数字 III

题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

解法一:哈希表

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

HASH_MAP_S *usrs = NULL;

int* singleNumber(int* nums, int numsSize, int* returnSize)
{
    HASH_MAP_S *cur, *next;
    int *ans = (int*)malloc(sizeof(int) * 2);
    *returnSize = 0;
    for (int i = 0; i < numsSize; i++) {
        HASH_FIND_INT(usrs, nums + i, cur);
        if (cur == NULL) {
            cur = (HASH_MAP_S*)malloc(sizeof(HASH_MAP_S));
            cur->key = nums[i];
            HASH_ADD_INT(usrs, key, cur);
            continue;
        }
        HASH_DEL(usrs, cur);
    }
    HASH_ITER(hh, usrs, cur, next) {
        ans[(*returnSize)++] = cur->key;
        HASH_DEL(usrs, cur);
        free(cur);
    }
    return ans;
}

解法二、亦或

只有两个出现一次的数字a和b,将整个数组元素进行亦或,根据亦或特性,相同为0相异为1,最终结果是a^b,取a^b的位数为1的最低位,将nums数组分成该位数为1和非1两个阵营,分别进行亦或,最后得到的两个结果就是a和b。

int* singleNumber(int* nums, int numsSize, int* returnSize)
{
    int *ans = (int *)calloc(2, sizeof(int));
    *returnSize = 2;
    int temp = 0;
    for (int i = 0; i < numsSize; i++) {
        temp ^= nums[i];
    }
    temp = (temp == INT_MIN ? temp : ((-temp) & temp));
    for (int i = 0; i < numsSize; i++) {
        if ((nums[i] & temp) != 0) {
            ans[0] ^= nums[i];
            continue;
        }
        ans[1] ^= nums[i];
    }
    return ans;
}

你可能感兴趣的:(leetcode,算法)