zoukankan      html  css  js  c++  java
  • Single Number III

    题目:

    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.

    For example:

    Given nums = [1, 2, 1, 3, 2, 5], return [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?

    分析:

    这题没想出来

    题目大意:一个数组,有两个元素出现了一次,其余元素都出现两次,让用线性时间复杂度和常量空间复杂度找出这两个数。

    解题思路:考虑位操作,对所有元素做异或操作,那么最后得到的值就是要求的两个元素异或得到的,那么找出其中为1的某一位,说明这一位两个数一个为0,一个为1,以这一位为标准,把数组的元素分为两组A、B,那么要求的两个元素肯定是一个在A组,一个在B组,而对这两组各自做异或操作,就可以得到两个数就是要求的。

    注意n&(~(n-1))表示取的n中的第一个为1的且其他置为0,(我也不知道为什么)

     1 class Solution {
     2 public:
     3     vector<int> singleNumber(vector<int>& nums) {
     4         int len = nums.size();
     5         int AxorB = 0;
     6         for(int i=0; i<len; i++){
     7             AxorB ^= nums[i];
     8         }
     9         int mask = AxorB & (~(AxorB-1));
    10         int A = 0;
    11         int B = 0;
    12         for(int i=0; i<len; i++){
    13             if((mask&nums[i])==0){
    14                 A ^= nums[i];
    15             }else{
    16                 B ^= nums[i];
    17             }
    18         }
    19         return vector<int>({A, B});
    20     }
    21 };
  • 相关阅读:
    云计算被视为继大型计算机、个人计算机、互联网之后的第4次IT产业革命,顺应了当前各行业整合计算资源和服务能力的要求(转)
    hdu1172猜数字
    or1200构建sopc系统之软件环境搭建
    Log4cpp介绍及使用
    JAVA实现HTTPserver端
    站点防止攻击
    opencv是什么
    RBAC权限管理
    一分钟制作U盘版BT3
    为开发用途mac电脑瘦身
  • 原文地址:https://www.cnblogs.com/raichen/p/4933277.html
Copyright © 2011-2022 走看看