zoukankan      html  css  js  c++  java
  • 只出现一次的数

    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]

    class Solution {
    public:
    vector<int> singleNumber(vector<int>& nums) {
        int x_xor_y = 0;
        for (int n: nums) {
            x_xor_y ^= n;
        }
        // 找到最后一位1 
        // 出现1表示,这一点处两个数的值不一样,一个为0一个为1,不然不可能异或出现1
        int mask = x_xor_y & ~(x_xor_y - 1);
        int x = 0;
        int y = 0;
        // x: XOR of a,a,b,b,x
        // y: XOR of c,c,y
        for (int n: nums) {
            if (n & mask) {
                x ^= n;
            } else {
                y ^= n;
            }
        }
        return vector<int> {x, y};
    }
    };

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

    class Solution {
    public:
        int singleNumber(int A[], int n) {
            int num = 0;
        for (size_t i = 0; i < n; ++i){
            num ^= A[i];
        }
        return num;
        }
    };

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

    int singleNumber(vector<int> AA) {
        int ones = 0, twos = 0;
        //int size = sizeof(AA) / sizeof(int);
        for (int i = 0; i < AA.size(); i++){
            ones = (ones ^ AA[i]) & ~twos;
            twos = (twos ^ AA[i]) & ~ones;
        }
        return ones;
    }
  • 相关阅读:
    数据库基本设计
    servlet 高级知识之Listener
    servlet 高级知识之Filter
    servlet-生命周期
    http协议概述
    javase高级技术
    javase高级技术
    IO之4种字节流拷贝文件方式对比
    Map 概述
    图解 数组,链表,2种数据结构
  • 原文地址:https://www.cnblogs.com/ddddddwwwxx/p/5878743.html
Copyright © 2011-2022 走看看