I am new to C++, and i tried to learn C++ while solving problems in leetcode.
Problems background:leetcode 697
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
unordered_map<int, int> count, first;
int res = 0, degree = 0;
for (int i = 0; i < nums.size(); ++i) {
// count first happen elements its frequency and it first occurrence index.
if (first.count(nums[i]) == 0)
first[nums[i]] = i;
if (++count[nums[i]] > degree) {
degree = count[nums[i]];
res = i - first[nums[i]] + 1;
} else if (count[nums[i]] == degree)
res = min(res, i - first[nums[i]] + 1);
}
return res;
}
};
int main() {
Solution s;
// vector<int> nums = { 1, 2, 2, 3, 1, 4, 2};
vector<int> nums = {1, 2, 2, 3, 1};
int res = s.findShortestSubArray(nums);
cout << res << endl;
return 0;
}
When i run this code, the result is 2 which is correct.
But when i try to print out the count map value after else if
, the result changed to 1 which is wrong and i have no idea how did that come from.
The code is like below.
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
unordered_map<int, int> count, first;
int res = 0, degree = 0;
for (int i = 0; i < nums.size(); ++i) {
// count first happen elements its frequency and it first occurrence index.
if (first.count(nums[i]) == 0)
first[nums[i]] = i;
if (++count[nums[i]] > degree) {
degree = count[nums[i]];
res = i - first[nums[i]] + 1;
} else if (count[nums[i]] == degree)
printf("count[nums[%d]] value is %d\n", i, count[nums[i]]);
res = min(res, i - first[nums[i]] + 1);
}
return res;
}
};
int main() {
Solution s;
// vector<int> nums = { 1, 2, 2, 3, 1, 4, 2};
vector<int> nums = {1, 2, 2, 3, 1};
int res = s.findShortestSubArray(nums);
cout << res << endl;
return 0;
}