leetcode - Single Number
今天開始刷leetcode上的題,爭取校招前刷過一遍,從AC率最高的題目開始刷,不廢話了,看題
?
題目: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?
?
個人思路:
1、對數組排序(從小到大或者從大到小)
2、從第一個數開始,與它后面一個數比較,若相同,說明數組中有兩個這樣的數,若不同,說明數組中只有一個這樣的數,也即是我們要獲得的數
?
代碼(main里面的代碼用于測試,提交時只需提交必要代碼即可):
1 #include <algorithm> 2 #include <iostream> 3 4 using namespace std; 5 6 class Solution 7 { 8 public: 9 int singleNumber(int A[], int n) 10 { 11 int index; 12 sort(&A[0], &A[n]); 13 for (index = 0; index < n; index += 2) 14 { 15 if (A[index] != A[index + 1]) 16 { 17 break; 18 } 19 } 20 21 return A[index]; 22 }; 23 }; 24 25 int main() 26 { 27 int A[] = {1, 2, 1, 3, 3, 4, 2, 5, 4}; 28 Solution s; 29 int single = s.singleNumber(A, 9); 30 cout << single << endl; 31 32 system("pause"); 33 return 0; 34 }?
上面的代碼先排序,然后遍歷數組,由于不是很清楚sort函數的時間復雜度,姑且當作O(nlogn)吧,總的來說,成功AC了,但整個代碼的時間復雜度為O(nlogn)
且題目的要求為:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
上網查找了線性時間復雜度算法,并且實踐了一下,在這里與大家分享,原文鏈接:http://www.cnblogs.com/changchengxiao/p/3413294.html
?
思路:
1、對于異或運算,有a ^ b = b ^ a和0^ a = a
2、那么遍歷數組時,將數組所有元素進行異或處理,相同的元素異或結果為0,則最終的異或結果即為只出現一次的元素
?
代碼:
1 #include <algorithm> 2 #include <iostream> 3 4 using namespace std; 5 6 class Solution 7 { 8 public: 9 int singleNumber(int A[], int n) 10 { 11 //個人思路 12 /* 13 int index; 14 sort(&A[0], &A[n]); 15 for (index = 0; index < n; index += 2) 16 { 17 if (A[index] != A[index + 1]) 18 { 19 break; 20 } 21 } 22 23 return A[index]; 24 */ 25 26 //網上思路 27 int result = 0; 28 for (int i = 0; i < n; ++i) 29 { 30 result ^= A[i]; 31 } 32 33 return result; 34 }; 35 }; 36 37 int main() 38 { 39 int A[] = {1, 2, 1, 3, 3, 4, 2, 5, 4}; 40 Solution s; 41 int single = s.singleNumber(A, 9); 42 cout << single << endl; 43 44 system("pause"); 45 return 0; 46 }?
原文鏈接中還有兩個擴展題,可以看看,好了,就到這吧
轉載于:https://www.cnblogs.com/laihaiteng/p/3776910.html
總結
以上是生活随笔為你收集整理的leetcode - Single Number的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【linux】学习笔记
- 下一篇: [转]Oracle DB 管理ASM实例