Leetcode刷题6--数组继续

本文介绍两种算法:一种用于从整数数组中找到只出现一次的元素,其他元素均出现两次;另一种解决类似问题但其他元素出现三次。文章提供具体实现代码,并强调算法的线性时间和空间效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.

Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?


解析: 如果对所有元素做异或运算,其结果为那个出现一次的元素,理解是a1 ^ a2 ^ ....,可以将所有相同元素交换至相邻位置,首先运算相同元素,则会产生(n - 1)/2个0异或积,剩余一个单一元素,他们的异或积为这个单一元素自己,得解。

只要出现偶数次都可以参考。

class Solution {

public:

    int singleNumber(int A[], int n) {

        int x = A[0];

        for (int i = 1; i < n ; ++i)

        {

            x ^= A[i];

        }

        return x;

    }

};


2.

Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

解析: 这题很明显是上个题的扩展,所以解法具有一定的通用性,仍然从位的角度着手,记录每位出现1的次数,这里是去除3个的,所以如果出现了三次,则可以去掉,剩下的就就是非三的那个数的有效位了,其他出现四次五次也可以这样。

class Solution {

public:

    int singleNumber(int A[], int n) {

        int M = sizeof(int) * 8;

        int count[M];

        fill_n(&count[0], M , 0);

        for (int i = 0; i < n ; ++i)

        {

            for (int j = 0; j < M ; ++j)

            {

                count[j] += (A[i] >> j) & 1;

                count[j] %= 3;

            }

        }

        int result = 0;

        for (int i = 0; i < M ; ++i)

        {

            result += count[i] << i;

        }

        return result;

    }

};




















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值