leetcode-27-exercise_bit maniputation
461. Hamming Distance
解題思路:
把兩個數的每一位和1比較,如果結果不同說明這兩位不同。要比較32次。
int hammingDistance(int x, int y) { int result = 0; for (int i = 0; i < 32; i++) { if (((x>>i)&0x1) != ((y>>i)&0x1)) { result ++; } } return result; }
477. Total Hamming Distance
解題思路:
因為數據是從0到10^9的,所以可以轉化為31位二進制數(10^9 = (10^3)^3 ~ (2^10)^3 = 2^30)。對於所有數的每一位,
計算該位置上1的個數和0的個數,那麽,這一位的總差異數應該是二者之積。取每一位的話,可以用右移來取。
int totalHammingDistance(vector<int>& nums) { int result = 0; int ones = 0; for (int i = 0; i < 31; i++) { for (int j = 0; j < nums.size(); j++) { if ((nums[j] >> i) & 0x1) ones ++; } result += ones * (nums.size() - ones); ones = 0; } return result; }
78. Subsets
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
解題思路:
首先,子集的數量應該是2^n。註意創建這種結構的寫法。
對於result來說,nums的每一個元素都可能存在也可能不存在。如果把j寫成二進制,如果第i位為1,就可以把nums[i]
放入result[j]。
vector<vector<int>> subsets(vector<int>& nums) { int size = pow(2, nums.size()); vector<vector<int> > result(size, vector<int>{}); for (int i = 0; i < nums.size(); i++) { for (int j = 0; j < size; j++) { if (j >> i & 0x1) result[j].push_back(nums[i]); } } return result; }
201. Bitwise AND of Numbers Range
解題思路:
要想確定整個範圍內的數,轉換為二進制時各個位置是否全為1,全部寫出來是沒有必要的。註意,此處只需要找出起始數共同的前綴就好了,
因為兩個數可以修改後面的部分,必然會存在有0的位置,所以通過右移找出共同前綴,記錄右移次數,再左移回來就好。
int rangeBitwiseAnd(int m, int n) { int i = 0; while (m != n) { m = m >> 1; n = n >> 1; i ++; } return (m << i); }
187. Repeated DNA Sequences
解題思路:
使用unordered_map。其中size_t是一個與機器相關的unsigned類型,其大小足以保證存儲內存中對象的大小。
用hash存子串,節省查找時間。如果子串重復次數等於2,就保留。如果這個子串重復次數多於2了,那肯定保存過了,就不用管了。
vector<string> findRepeatedDnaSequences(string s) { vector<string> result; if (s.length() <= 10) return result; hash<string> h; unordered_map<size_t, int> m; for (int i = 0; i <= s.length() - 10; i++) { string sub = s.substr(i, 10); m[h(sub)] ++; if (m[h(sub)] == 2) { result.push_back(sub); continue; } } return result; }
leetcode-27-exercise_bit maniputation