只出现一次的数字
int singleNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
for(int i = 0, j = 1; j < nums.size(); i += 2, j += 2){
if(nums[i] != nums[j]) return nums[i];
}
return nums[nums.size() - 1];
}
int singleNumber(vector<int>& nums) {
int result = 0;
for(int e : nums)
result ^=e;
return result;
}
电话号码的字母组合
vector<string> letterCombinations(string digits) {
vector<string> a{"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> c;
if(digits.empty())
return c;
c.push_back("");
for (int i=0;i<digits.size();i++)
{
int res=digits[i]-'2';
int len=c.size();
for(int i = 0;i<len;i++)
{
for (auto m:a[res])
{
c.push_back(c[i]+m);
}
}
c.erase(c.begin(),c.begin()+len);
}
return c;
}
杨辉三角OJ
vector<vector<int>> generate(int numRows) {
vector<vector<int>> a(numRows);
if(numRows == 0)
return a;
for(int i = 0; i < numRows; ++ i )
{
for(int j = 0; j <= i; ++ j)
{
if(j == 0 || j == i)
a[i].push_back(1);
else
a[i].push_back(a[i-1][j-1] + a[i-1][j]);
}
}
return a;
}
删除排序数组中的重复项
int removeDuplicates(vector<int>& nums) {
int i = 0;
for (int j = 0; j < nums.size(); ++j) {
if (i == 0 || nums[i-1] != nums[j])
nums[i++] = nums[j];
}
return i;
}
只出现一次的数字 II——331
int singleNumber(vector<int>& nums) {
vector<int> bits(32);
int ans = 0;
for (int i = 0; i < 32; i++) {
for (int j = 0; j < nums.size(); j++)
bits[i] += (nums[j] >> i) & 1;
ans |= (bits[i] % 3) << i;
}
return ans;
}
int singleNumber(vector<int>& nums) {
int ones = 0, twos = 0;
for(int i=0; i<nums.size(); ++i){
ones = (ones^nums[i]) & ~twos;
twos = (twos^nums[i]) & ~ones;
}
return ones;
}
只出现一次的数字 II——1,1,2,3
vector<int> singleNumber(vector<int>& nums) {
int sum = 0,b = 1;
for(auto num : nums)
sum ^= num;
while((sum&1) == 0){
sum >>= 1;
b <<= 1;
}
int num1 = 0,num2=0;
for(auto i:nums){
if((i&b) != 0)
num1 ^= i;
else
num2 ^= i;
}
return {num2,num1};
}
数组中出现次数超过一半的数字
int MoreThanHalfNum_Solution(vector<int> numbers) {
sort(numbers.begin(),numbers.end());
int key = numbers[numbers.size()/2];
int count = 0;
for (int i = 0; i < numbers.size(); ++i) {
if(key == numbers[i])
++ count;
}
if (count>numbers.size()/2)
return key;
return 0;
}
连续子数组最大的和
int FindGreatestSumOfSubArray(vector<int> array)
{
if(array.empty())
return 0;
int cur_sum = array[0];
int max_sum = array[0];
for(int i = 1; i < array.size(); ++i)
{
if(cur_sum <= 0)
cur_sum = array[i];
else
cur_sum += array[i];
if(cur_sum > max_sum)
max_sum = cur_sum;
}
return max_sum;
}