數組中出現一次的兩個數 leetcode Single Number III

來源:互聯網
上載者:User

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:
The order of the result is not important. So in the above example, [5, 3] is also correct.

Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? 解題思路:有一個數組,其中只有兩個數出現一次,其他數均出現兩次,求出這兩個數。參考signal number的第二種解法:http://blog.csdn.net/sinat_24520925/article/details/45576735 我們將這個數組分成兩個數組,每個數組中都只有一個元素出現一次。也就是先異或所有元素,得到resultExclusive,找到resultExclusive中二進位表示的由右向左的第一位1,則表明數組中有一個一次出現的數該位的值不同,一個為0、另一個為0.下面就好做了,將數組中該位均為0的異或,均為1的異或就可求得只出現一次的那兩個數。 代碼如下:

class Solution {public:    vector<int> singleNumber(vector<int>& nums) {        vector<int> res;        if(nums.size()==0) return res;        res.push_back(0);        res.push_back(0);        int resultExclusive=0;        for(int i=0;i<nums.size();i++)        resultExclusive^=nums[i];        int indexof1=0;        while(((resultExclusive&1)==0)&&(indexof1<8*sizeof(int)))        {            resultExclusive=resultExclusive>>1;            ++indexof1;        }        for(int i=0;i<nums.size();i++)        {            if((nums[i]>>indexof1)&1==1)            res[0]^=nums[i];            else            res[1]^=nums[i];        }        return res;    }};
值得注意的是::
(resultExclusive&1)==0)
(resultExclusive&1)一定要加(),否則因為==的優先順序高於&,會導致while迴圈無法進入。。。。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.