Skip to content

611. Valid Triangle Number 👍

  • Time: $O(n^2)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
 public:
  int triangleNumber(vector<int>& nums) {
    if (nums.size() < 3)
      return 0;

    int ans = 0;

    ranges::sort(nums);

    for (int k = nums.size() - 1; k > 1; --k) {
      int i = 0;
      int j = k - 1;
      while (i < j)
        if (nums[i] + nums[j] > nums[k]) {
          // (nums[i], nums[j], nums[k])
          // (nums[i + 1], nums[j], nums[k])
          // ...
          // (nums[j - 1], nums[j], nums[k])
          ans += j - i;
          --j;
        } else {
          ++i;
        }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
  public int triangleNumber(int[] nums) {
    if (nums.length < 3)
      return 0;

    int ans = 0;

    Arrays.sort(nums);

    for (int k = nums.length - 1; k > 1; --k) {
      int i = 0;
      int j = k - 1;
      while (i < j)
        if (nums[i] + nums[j] > nums[k]) {
          // (nums[i], nums[j], nums[k])
          // (nums[i + 1], nums[j], nums[k])
          // ...
          // (nums[j - 1], nums[j], nums[k])
          ans += j - i;
          --j;
        } else {
          ++i;
        }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def triangleNumber(self, nums: list[int]) -> int:
    ans = 0

    nums.sort()

    for k in range(len(nums) - 1, 1, -1):
      i = 0
      j = k - 1
      while i < j:
        if nums[i] + nums[j] > nums[k]:
          ans += j - i
          j -= 1
        else:
          i += 1

    return ans