练习整理
Leetcode 611. Valid Triangle Number (Medium)
将array排序,令nums[a] < nums[b] < nums[c]
。双指针问题的重点是找到单调性。
外层循环遍历c
,在循环内让a
和b
作为双指针从两端(nums[0], nums[c-1]
)向中心扫描,如果想让nums[a] + nums[b]
的值增大,则只能增大a
下标,反之只能减小b
下标,这就是单调性,能够避免两重循环遍历a
和b
。
如果某个时刻满足nums[a] + nums[b] > nums[c]
,说明(nums[a ~ b-1], nums[b], nums[c])
都是合法三元组(类似 Leetcode 259. 3Sum Smaller)。
class Solution {
public:
int triangleNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
int numTriplets = 0;
int n = nums.size();
// nums[a] < nums[b] < nums[c]
for (int c = n - 1; c >= 2; --c) {
int a = 0, b = c - 1;
while (a < b) {
if (nums[a] + nums[b] > nums[c]) {
// nums[a ~ b-1] + nums[b] > nums[c], so there are (b-a) valid triplets.
numTriplets += b - a;
--b;
} else {
++a;
}
}
}
return numTriplets;
}
};