Single Number,singlenumber

來源:互聯網
上載者:User

Single Number,singlenumber

本文是在學習中的總結,歡迎轉載但請註明出處:http://blog.csdn.net/pistolove/article/details/42713315



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?


思路:

(1)題意為給定一個整形數組,其中數組中除了一個元素之外,其它任意元素都出現兩次,求只出現一次的元素。

(2)由於題目限制了時間複雜度為線性,即不能出現多次for迴圈,且建議最好不要申請額外的空間。這樣,我們就需要思考,如何在遍曆數組一次的情況下找出出現一次的元素。考慮到能否想辦法把相同的元素都消除掉,這裡我們就需要運用不常見的特殊運算子“^”— 按位異或運算。我們知道異或運算相同的位會消除,例4^4=(二進位)10^(二進位)10=(二進位)00,這樣就消除了相同的數字。即使數組中相同數字是非連續的,根據加法的交換律,能夠得到同樣的結果。

(3)希望本文對你有所協助。

演算法代碼實現如下:

/** * @author liqq */public static int singleNumber(int[] A) {if (A.length == 0)return A[0];int x = A[0];for (int i = 1; i < A.length; i++) {x = x ^ A[i];}return x;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.