Created
May 28, 2024 11:34
-
-
Save shitu13/7ec698daf4e531536459a67a0e87af44 to your computer and use it in GitHub Desktop.
Count Negative Numbers in a Sorted Matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Approach 1 | |
// Complexity: O(n^2) | |
class Solution { | |
public: | |
int countPairs(vector<int>& nums, int target) { | |
int result = 0; | |
for(int i=0; i<nums.size(); i++){ | |
for(int j=i+1; j<nums.size();j++){ | |
if(nums[i]+nums[j]<target){ | |
result++; | |
} | |
} | |
} | |
return result; | |
} | |
}; | |
// Approach 2 | |
// Complexity: O(n*log n) | |
class Solution { | |
public: | |
int countPairs(vector<int>& nums, int target) { | |
int cnt = 0; | |
int l = 0; | |
int r = nums.size() - 1; | |
sort(nums.begin(), nums.end()); | |
while (l != r) { | |
if (nums[l] + nums[r] < target) { | |
cnt += (r - l); | |
l++; | |
} else | |
r--; | |
} | |
return cnt; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment