611. Valid Triangle Number

Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.

Example 1:

Input: [2,2,3,4]
Output: 3
Explanation:
Valid combinations are: 
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3

Note:

  1. The length of the given array won't exceed 1000.
  2. The integers in the given array are in the range of [0, 1000].

Rust Solution

struct Solution;

impl Solution {
    fn triangle_number(mut nums: Vec<i32>) -> i32 {
        let mut res = 0;
        let n = nums.len();
        nums.sort_unstable();
        for i in (2..n).rev() {
            let mut l = 0;
            let mut r = i - 1;
            while l < r {
                if nums[l] + nums[r] > nums[i] {
                    res += r - l;
                    r -= 1;
                } else {
                    l += 1;
                }
            }
        }
        res as i32
    }
}

#[test]
fn test() {
    let nums = vec![2, 2, 3, 4];
    let res = 3;
    assert_eq!(Solution::triangle_number(nums), res);
}

Having problems with this solution? Click here to submit an issue on github.