[Leetcode] single number 找单个数
生活随笔
收集整理的這篇文章主要介紹了
[Leetcode] single number 找单个数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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?
題意:給定一未排序的數組,其中只有一個數僅出現一次,其余都出現兩次,找到僅出現一次的這個數。
思路:一般的暴力解法或者先排序,后遍歷。顯然這兩種種做法不行,時間復雜度上沒法滿足線性。所以采用邏輯異或來解題。邏輯異或有幾個特點:
一、異或滿足交換律;二、相同兩個數異或為0;三、0異或一個數為那個數本身。十位數的異或,先將其轉變二進制,然后進行異或。參考了LeetCode OJ代碼如下:
1 class Solution { 2 public: 3 int singleNumber(int A[], int n) 4 { 5 int res=0; 6 for(int i=0;i<n;++i) 7 { 8 res^=A[i]; 9 } 10 return res; 11 } 12 };同樣的思路還有一種解法,牛客網@setsail,這種解法也是根據相同數異或為0的特性,找到僅出現一次的那個數。
1 class Solution { 2 public: 3 int singleNumber(int A[], int n) 4 { 5 if(n==1) 6 return A[0]; 7 while(n>=2) 8 { 9 A[n-2]^=A[n-1]; 10 n--; 11 } 12 return A[0]; 13 } 14 };?
轉載于:https://www.cnblogs.com/love-yh/p/7198768.html
總結
以上是生活随笔為你收集整理的[Leetcode] single number 找单个数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: easyDarwin--开源流媒体实现
- 下一篇: 开发环境配置