【刷题笔记】双指针

练习整理

Leetcode 611. Valid Triangle Number (Medium)

Leetcode Link

将array排序,令nums[a] < nums[b] < nums[c]。双指针问题的重点是找到单调性。

外层循环遍历c,在循环内让ab作为双指针从两端(nums[0], nums[c-1])向中心扫描,如果想让nums[a] + nums[b]的值增大,则只能增大a下标,反之只能减小b下标,这就是单调性,能够避免两重循环遍历ab

如果某个时刻满足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;
  }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值