-1

The error comes from one Leetcode test case for this problem. I copy my solution so that the particular test case will break.

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        sort(nums.begin(), nums.end());



        for (int i = 0; i < nums.size() - 2; i++) {
            cout << "nums.size(): " << nums.size() << endl;
            if (i > 0 && nums[i] == nums[i-1])
                continue;
            int left = i + 1, right = nums.size() - 1;
            while(left < right) {
                int s = nums[i] + nums[left] + nums[right];
                if (s > 0) right--;
                else if (s < 0) left++;
                else {
                    res.push_back({nums[i], nums[left], nums[right]});
                    while(left + 1 < right && nums[left] == nums[left+1]) left++;
                    while(right - 1 > left && nums[right] == nums[right-1]) right--;
                    left ++; right--;
                }
            }
        }

        return res;
    }
};

Last executed input []

I'm confused because in this case, since nums is an empty vector, nums.size() should be 0, and since i < nums.size() - 2 = -2 is not met, the for loop shouldn't be executed but somehow I got a runtime error. Could someone please explain why this breaks? Thanks in advance!

user8822312
  • 255
  • 4
  • 14

2 Answers2

1

nums.size() return a unsigned value,-2 cause overflow.

(int)nums.size()-2 can solve it.

liuyulvv
  • 154
  • 10
1

The problem is that the size() function returns an unassigned int, and you're comparing it to i, which is a signed int.

Turn this line...

for (int i = 0; i < nums.size() - 2; i++) {

Into this...

for (int i = 0; i < ((int)nums.size()) - 2; i++) {

And here's a link to someone else with a similar problem, if you wanna read more about other solutions...

What is wrong with my For loops? i get warnings: comparison between signed and unsigned integer expressions [-Wsign-compare]

user4581301
  • 33,082
  • 7
  • 33
  • 54
Corey M
  • 11
  • 2