136. Single Number
给定一个数组,找出frequency为1的数字(有唯一解),其他数字的frequency为2
- 先排序,再比对查找, O ( n log n ) O(n log n) O(nlogn)
- bit 操作,XOR 的性质: A ⊕ A = 0 Aoplus A = 0 A⊕A=0, A ⊕ A ⊕ = A A oplus A oplus = A A⊕A⊕=A, …
137. Single Number II
class Solution {
public:
int singleNumber(vector<int>& nums) {
vector<int> bitCount(32, 0);
for (int i = 0; i < 32; i++) {
int mask = 1 << i;
for (auto num: nums) {
if (num & mask) {
bitCount[i]++;
}
}
}
int ans = 0;
for (int i = 0; i < 32; i++) {
if (bitCount[i] % 3) {
ans += 1 << i;
}
}
return ans;
}
};
260. Single Number III
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int axorb = 0;
for (int num: nums) {
axorb ^= num;
}
int bit = -1;
for (int i = 0; i < 32; i++) {
if (axorb & (1 << i)) {
bit = i;
break;
}
}
// bit is the rightmost digit that a differs from b
int first = 0;
for (int a: nums) {
if (a & (1 << bit)) {
first ^= a;
}
}
// identify the first unique number whose digit at *bit* digit is 1
int second = axorb ^ first;
// inverse operation
return {first, second};
}
};
123. Best Time to Buy and Sell Stock III
这个DP可以有!
class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy1 = INT_MIN, buy2 = INT_MIN, buy1sell1 = 0, buy2sell2 = 0;
for (int i = 0; i < prices.size(); i++) {
buy1 = max(buy1, -prices[i]);
buy1sell1 = max(buy1sell1, prices[i] + buy1);
buy2 = max(buy2, buy1sell1-prices[i]);
buy2sell2 = max(buy2sell2, prices[i] + buy2);
}
return max(buy1sell1, buy2sell2);
}
};
2012. Sum of Beauty in the Array
class Solution {
public:
int sumOfBeauties(vector<int>& nums) {
int n = nums.size();
vector<int> left(n, INT_MIN), right(n, INT_MAX);
left[0] = nums[0];
right[n-1] = nums[n-1];
for (int i = 1; i < n; i++) {
left[i] = max(left[i-1], nums[i]);
}
for (int i = n - 2; i >= 0; i--) {
right[i] = min(right[i+1], nums[i]);
}
int sum = 0;
for (int i = 1; i < n - 1; i++) {
if (nums[i] > left[i-1] && nums[i] < right[i+1]) {
sum += 2;
} else if (nums[i] > nums[i-1] && nums[i] < nums[i+1]) {
sum += 1;
}
}
return sum;
}
};
930. Binary Subarrays With Sum
class Solution {
public:
int numSubarraysWithSum(vector<int>& nums, int goal) {
unordered_map<int,int> c({{0,1}});
int sum = 0;
int res = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
res += c[sum-goal];
c[sum]++;
}
return res;
}
};
总结
写到这里也结束了,在文章最后放上一个小小的福利,以下为小编自己在学习过程中整理出的一个关于 java开发 的学习思路及方向。从事互联网开发,最主要的是要学好技术,而学习技术是一条慢长而艰苦的道路,不能靠一时激情,也不是熬几天几夜就能学好的,必须养成平时努力学习的习惯,更加需要准确的学习方向达到有效的学习效果。
由于内容较多就只放上一个大概的大纲,需要更及详细的学习思维导图的 点击我的Gitee获取。
还有 高级java全套视频教程 java进阶架构师 视频+资料+代码+面试题!
全方面的java进阶实践技术资料,并且还有技术大牛一起讨论交流解决问题。