201. Bitwise AND of Numbers Range

描述

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

For example, given the range [5, 7], you should return 4.

分析

101->111
10->11
1->1


m==2，n==4，返回

010->100
1->10


class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int count=0;
while(m!=n){
count++;
m=m>>1;
n=n>>1;
}
return m<<count;
}
};


78. Subsets

描述

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example, If nums = [1,2,3], a solution is:

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]


分析

[
[ ]
]


[
[ ]
[1]
]


[
[ ]
[1]
[1 2]
[2]
]


[
[ ]
[1 2 3]
[2 3]
[3]
]


………………

/*Solution1 ,Iteration*/
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int>> res(1);
for(int i=0;i<S.size();++i){
int size=res.size();
for(int j=0;j<size;j++){
res.push_back(res[j]);
res.back().push_back(S[i]);
}
}
return res;
}
};


subsets([1 2 3 4])=[]
//push(1)
[1,subsets[2 3 4]]
//pop,push(2)
[2,subsets[3,4]]
//pop,push(3)
[3,subsets[4]]
//pop,push(4)
[4,subsets[]]
//pop


/*Solution2 Recursion*/
class Solution {
private:
void backtracking(vector<int> & nums,vector<int> & sub,vector<vector<int>> & subs,int start){
subs.push_back(sub);
for(int i=start;i<nums.size();++i){
sub.push_back(nums[i]);
backtracking(nums,sub,subs,i+1);
sub.pop_back();
}
}
public:
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int>> subs;
vector<int> sub;
backtracking(S,sub,subs,0);
return subs;
}
};


Power of K问题

231. Power of Two

Given an integer, write a function to determine if it is a power of two.

1   1
2   10
4   100
8   1000
16  10000
32  100000


class Solution {
public:
bool isPowerOfTwo(int n) {
return n>0&&!(n&(n-1));
}
};


326. Power of Three

Given an integer, write a function to determine if it is a power of three.

3的幂次方似乎没有什么特殊的性质（反正我没看出来），所以我们就要利用一下数学知识了，即:如果一个数是3的整数幂次方，那么其以3为底的对数必然是一个整数。

n=243时:

log(243) = 5.493061443340548    log(3) = 1.0986122886681098
==> log(243)/log(3) = 4.999999999999999


class Solution {
public:
bool isPowerOfThree(int n) {
double res=log10(n)/log10(3);
return (res-(int)(res))==0? true:false;
}
};


class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && (1162261467 % n == 0);
}
};


(然而你都知道3的幂次方有哪些数了你还算啥呀？！)

342. Power of Four

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example: Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?

1   0000 0001
4   0000 0100
16  0001 0000

2   0000 0010
8   0000 1000


class Solution {
public:
bool isPowerOfFour(int num) {
return num>0&&!(num&(num-1))&&(num&(0x55555555));
}
};


299. Bulls and Cows

You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called “bulls”) and how many digits match the secret number but locate in the wrong position (called “cows”). Your friend will use successive guesses and hints to eventually derive the secret number.

For example:

Secret number:  "1807"
Friend's guess: "7810"


Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)

Write a function to return a hint according to the secret number and friend’s guess, use A to indicate the bulls and B to indicate the cows. In the above example, your function should return “1A3B”.

Please note that both secret number and friend’s guess may contain duplicate digits, for example:

Secret number:  "1123"
Friend's guess: "0111"


In this case, the 1st 1 in friend’s guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return “1A1B”.

You may assume that the secret number and your friend’s guess only contain digits, and their lengths are always equal.

class Solution {
public:
string getHint(string secret, string guess) {
if(secret.empty()||guess.empty())
return "0A0B";
vector<int> countS(10,0);
vector<int> countG(10,0);
string res;
int countA=0,countB=0;
for(int i=0;i<secret.size();i++){
if(secret[i]==guess[i])
countA++;
else{
countS[secret[i]-'0']++;
countG[guess[i]-'0']++;
}
}
for(int i=0;i<countS.size();i++)
countB+=min(countS[i],countG[i]);
res=to_string(countA)+'A'+to_string(countB)+'B';
return res;
}
};


290. Word Pattern

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples:

pattern = “abba”, str = “dog cat cat dog” should return true.

pattern = “abba”, str = “dog cat cat fish” should return false.

pattern = “aaaa”, str = “dog cat cat dog” should return false.

pattern = “abba”, str = “dog dog dog dog” should return false.

Notes:

You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> res=divideStr(str);
unordered_map<string,string> hash;
istringstream in(str);
int i=0;
for(string word;in>>word;i++){
if(hash.find(pattern[i])!=hash.end()){
if(hash[pattern[i]]!=word)
return false;
}
else{
for(unordered_map<char,string>::iterator it=hash.begin();it!=hash.end();it++){
if(it->second==word)
return false;
}
hash[pattern[i]]=word;
}
}
return i==pattern.size();
}
};


205. Isomorphic Strings

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example, Given “egg”, “add”, return true.

Given “foo”, “bar”, return false.

Given “paper”, “title”, return true.

class Solution {
public:
bool isIsomorphic(string s, string t) {
int map1[256]={0},map2[256]={0},i=0;
for(i=0;i<s.size();i++){
if(map1[s[i]]!=map2[t[i]])
return false;
map1[s[i]]=map2[t[i]]=i+1;
}
return i==s.size();
}
};


49. Group Anagrams

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return:

[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]



Note: All inputs will be in lower-case.

class Solution {
private:
string strSort(string& str){
int count[26]={0},p=0,size=str.size();
string res(size,'a');
for(int i=0;i<str.size();i++)
count[str[i]-'a']++;
for(int i=0;i<26;i++)
for(int j=0;j<count[i];j++)
res[p++]+=i;
return res;
}
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
if(strs.empty())
return {};
unordered_map<string,vector<string>> hash;
vector<vector<string>> anagrams;
for(string s:strs){
string t=strSort(s);
// sort(t.begin(),t.end());
hash[t].push_back(s);
}
for(unordered_map<string,vector<string>>::iterator pos=hash.begin();pos!=hash.end();pos++){
vector<string> anagram(pos->second.begin(),pos->second.end());
anagrams.push_back(anagram);
}
return anagrams;
}
};


Majority Voting Algorithm

The algorithm is carried out in two steps:

1.Eliminate all elements except one.

Iterating through the array of numbers, maintain a current candidate and a counter initialized to 0. With the current element x in iteration, update the counter and (possibly) the candidate: if the counter is 0, set the current candidate to x and the counter to 1. If the counter is not 0, increment or decrement the counter based on whether x is the current candidate.

2.Determine if the remaining element is a valid majority element.

With the candidate acquired in step 1, iterate through the array of numbers and count its occurrences. Determine if the result is more than half of the sequence’s length. If so, the candidate is the majority. Otherwise, the sequence doesn’t contain a majority.

JAVA实现如下:

public int majorityElement(int[] num) {
int n = num.length;
int candidate = num[0], counter = 0;
for (int i : num) {
if (counter == 0) {
candidate = i;
counter = 1;
} else if (candidate == i) {
counter++;
} else {
counter--;
}
}

counter = 0;
for (int i : num) {
if (i == candidate) counter++;
}
if (counter <= n / 2) return -1;
return candidate;

}


169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

class Solution {
public:
int majorityElement(vector<int>& nums) {
int curIndex=0,count=0,i=0;
for(i=0;i<nums.size();i++){
nums[curIndex]==nums[i]?count++:count--;
if(!count){
curIndex=i;
count=1;
}
}
return nums[curIndex];
}
};


229. Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

Hint:

How many majority elements could it possibly have?

Do you have a better hint?

class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int curIndex1=0,curIndex2=0,count1=0,count2=0;
int size=nums.size(),i=0,tri=size/3;
vector<int>res;
for(i=0;i<nums.size();i++){
if(nums[i]==nums[curIndex1])
count1++;
else if(nums[i]==nums[curIndex2])
count2++;
else if(!count1){
count1=1;
curIndex1=i;
}
else if(!count2){
count2=1;
curIndex2=i;
}
else{
count1--;
count2--;
}
}
count1=0;
count2=0;
for(i=0;i<nums.size();i++){
if(nums[i]==nums[curIndex1])
count1++;
else if(nums[i]==nums[curIndex2])
count2++;
}
if(count1>tri)
res.push_back(nums[curIndex1]);
if(count2>tri)
res.push_back(nums[curIndex2]);
return res;
}
};