[leetcode]260. Single Number III

本文介绍了一种线性时间复杂度的算法来找出数组中仅出现一次的两个元素,并提供了详细的实现步骤及代码示例。

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

链接:https://leetcode.com/problems/single-number-iii/description/

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

Example:

Input:  [1,2,1,3,2,5]
Output: [3,5]

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
class Solution{
public:
    vector<int> singleNumber(vector<int>& nums)
    {
        vector<int> res(2,0);
        int mark=0;
        for(auto num:nums)
            mark^=num;
        
        //The statement "int lowbit=mark&(~(mark-1));" can find the rightmost set bit. For     
        //example, for mark = 4, bit = 2, i.e., lowbit is 
        //"00000000000000000000000000000010" in binary format  , the right first 1 in 
        //binary format
        int lowbit=mark&(~(mark-1));
        for(auto num:nums)
        {
            if((num&lowbit)==0)
                res[0]^=num;
            else
                res[1]^=num;

        }
        return res;
    }
};

 

LeetCode的第260题中,题目被称为“只有一个公共元素的数组 II”。这是一道关于数组操作的数据结构和算法题目。给定两个已经排序的整数数组 nums1 和 nums2,你需要找出它们之间的一个共同的元素,这个元素在每个数组中都只出现一次。 该问题的目标是找到这样的一个公共元素,并返回它的值。例如,如果nums1 = [1, 2, 2, 4] 和 nums2 = [2, 2, 8, 10],那么唯一的公共单次出现的元素是2。 为了解决这个问题,你可以采用一种类似于双指针的方法。从两个数组的起始位置开始遍历,每次比较当前指针对应的元素。如果元素相等且在各自的数组中都是第一次出现(即前一个出现的位置比当前位置大),就将这个元素添加到结果中并继续向后移动指针。如果遇到不同的元素,则移动较小的那个指针的所在数组的指针。 Python 或 C++ 等语言中,可以实现一个循环或者递归的解决方案,直到找到共同的单次出现元素或遍历完其中一个数组。这里是一个简单的 Python 示例: ```python def singleNumber(nums1, nums2): i, j = 0, 0 count = {} while i < len(nums1) and j < len(nums2): if nums1[i] not in count or nums2[j] not in count: count[nums1[i]] = 1 i += 1 elif nums2[j] not in count: count[nums2[j]] = 1 j += 1 else: del count[nums1[i]] del count[nums2[j]] i += 1 j += 1 # 如果有一个数组没遍历完,剩下的最后一个元素就是公共唯一元素 return list(count.keys())[0] if i < len(nums1) else list(count.keys())[-1] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值