Skip to content

Commit

Permalink
Create 3sum-smaller.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 committed Aug 17, 2015
1 parent a0286af commit a465bcd
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions C++/3sum-smaller.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Time: O(n^2)
// Space: O(1)

class Solution {
public:
int threeSumSmaller(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
const int n = nums.size();

int count = 0;
for (int k = 2; k < n; ++k) {
int i = 0, j = k - 1;
while (i < j) { // Two Pointers, linear time.
if (nums[i] + nums[j] >= target - nums[k]) {
--j;
} else {
count += j - i;
++i;
}
}
}

return count;
}
};

0 comments on commit a465bcd

Please sign in to comment.