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?
class Solution {public: vector<int> singleNumber(vector<int>& nums) { }};給定一個數字nums的數組,其中恰好兩個元素只出現一次,所有其他元素出現正好兩次。 找到只出現一次的兩個元素。
例如:
給定nums = [1,2,1,3,2,5],return [3,5]。
注意: 結果的順序并不重要。 所以在上面的例子中,[5,3]也是正確的。 您的算法應以線性運行時復雜性運行。 你能實現它只使用恒定的空間復雜性?
首先比較好想到的還是排序,將這些數排序后相鄰兩個依次比較,一直比較到第二個沒有相同數的值為止,就得到答案了。 當然,還發現這個題和以前做的:http://blog.csdn.net/zzlcsdn2017/article/details/59616340Single Number I(以后稱I)有異曲同工之妙,這道題依然是需要用異或來求解: 如果還按I中方式,將所有數字都異或后得到的是其中單獨的兩個數的異或值,因為這兩個數不同,異或后一定存在“1”,而其他值都相互異或為“0”了。那么就可以利用“1”(只用一個就夠了,即使可能存在多個,就設定為從低位到高位的第一個“1”,假設為a位)將原來的數組分為兩個,一個所有數字a位全是1,另一個是剩下的數字,相同的數字兩兩都分在了同一個組里,而不同的兩個數字也被分開了,最后分別對這兩個數組再一次全部異或,便分別得到我們想要的兩個數字。
(94.69%)還是比較強的
class Solution {public: vector<int> singleNumber(vector<int>& nums) { int ax = 0; int a = 0, b = 0; for (int i = 0; i<nums.size(); i++) { ax ^= nums[i]; } //for (int item : nums) { // ax ^= item; //} int lastb = (ax & (ax - 1)) ^ ax; for (int item : nums) { if (item & lastb) { a ^= item; } else { b ^= item; } } /*for (int i = 0; i < nums.size();i++) { if (nums[i] & lastb) { a ^= nums[i]; } else { b ^= nums[i]; } }*/ return vector<int>{a, b}; }}; int lastb = (ax & (ax - 1)) ^ ax;//求二進制ax最小的1所在地。 第二個for循環直接合并步驟,用if省去了分組的事情,直接將新聞熱點
疑難解答
圖片精選