0

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;
}
Peter Tsung
  • 915
  • 2
  • 10
  • 20
  • 2
    You are missing {} after else if – SBF Apr 26 '20 at 10:00
  • One reason why some people say you should aways include `{}` even if you only have a single statement (not that I agree, but it's one argument in favour). – john Apr 26 '20 at 10:02
  • Does this answer your question? [Why is it considered a bad practice to omit curly braces?](https://stackoverflow.com/questions/359732/why-is-it-considered-a-bad-practice-to-omit-curly-braces) – L. F. Apr 26 '20 at 11:37

1 Answers1

1

Replace

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);

with

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);
}

You should always use {} when size of a block exceeds one line.

SarojKr
  • 65
  • 3
  • 12