51. 數組中只出現一次的數字
class Solution {
public:
void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {
//使用異或的方式,二進制下,出現過兩次的數都會相互抵消掉,只留下出現一次的數
//因爲有兩個數字,將所有數字異或後,會得到這兩個數字異或的結果
//分析結果得出兩個數字二進制下不同的位置,即異或值爲1的位置
//根據該信息將數組分成兩部分,分別異或,可得出兩值
int temp=0;
for (int i=0;i<data.size();i++){
temp=temp^data[i];
}
int loc=0;
while(temp>0){
if(temp%2) break;
loc++;
temp=temp>>1;
}
*num1=0;
*num2=0;
for (int i=0;i<data.size();i++){
temp=data[i];
temp=temp>>loc;
if(temp&1){
*num1^=data[i];
}
else{
*num2^=data[i];
}
}
}
};
52. 和爲S的兩個數字
class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> array,int sum) {
vector<int> res;
if(array.size()<=1) return res;
int low=0,high=array.size()-1;
while(low<high){
if(array[low]+array[high]>sum)
high--;
else if(array[low]+array[high]<sum)
low++;
else{
res.push_back(array[low]);
res.push_back(array[high]);
break;
}
}
return res;
}
};
53. 和爲S的連續整數序列
確定序列範圍後,從最小的兩個值開始遍歷,比sum小則結果中加進序列後一位,比sum大則減去結果中最小的一位
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
vector<vector<int>> res;
if(sum<1) return res;
vector<int> temp_res;
//至少包含兩個數,所以是從1 到 sum/2+1
int low=1,high=2;
int temp_sum=3;
while(low<high && high<=sum/2+1){
if(temp_sum==sum){
for(int i=low;i<=high;i++)
temp_res.push_back(i);
res.push_back(temp_res);
temp_res={};
temp_sum-=low;
low++;
}
else if(temp_sum<sum){
high++;
temp_sum+=high;
}
else if(temp_sum>sum){
temp_sum-=low;
low++;
}
}
return res;
}
};
54. 翻轉單詞順序列
有嘗試寫簡單點,最後刪除一下多餘的空格,但這樣總是出現一個問題說是空格格式或者換行格式出錯,不知道問題在哪裏。。
class Solution {
public:
string ReverseSentence(string str) {
if(str.empty()) return str;
string res="";
stack<char> temp;
char emp=' ';
for(int i=str.size()-1;i>=0;i--){
if(str[i]!=' '){
temp.push(str[i]);
}
else{
while(!temp.empty()){
char pop1=temp.top();
res.push_back(pop1);
temp.pop();
}
res.push_back(str[i]);
}
}
while(!temp.empty()){
char pop1=temp.top();
res.push_back(pop1);
temp.pop();
}
//res=res.substr(0,res.size()-1);
return res;
}
};
55. 左旋轉字符串
class Solution {
public:
string LeftRotateString(string str, int n) {
if(str.size()<=0 || n<0) return "";
string temp;
while(n>str.size())
n-=str.size();
for(int i=0;i<n;i++)
temp.push_back(str[i]);
str=str.substr(n,str.size());
str=str+temp;
return str;
}
};