Algorithm


Problem Name: 611. Valid Triangle Number

Given an integer array nums, return 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: nums = [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

Example 2:

Input: nums = [4,2,3,4]
Output: 4

 

Constraints:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    int triangleNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int count = 0, n = nums.size();
        for(int i = 0; i  <  n; i++)
            for(int j = i + 1; j  <  n; j++)
                for(int k = j + 1; k  <  n; k++)
                    if(nums[i] + nums[j] > nums[k]) count++;
        return count;
    }
};

class Solution {
public:
    int triangleNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int count = 0, n = nums.size();
        for(int i = n - 1; i > 1; --i) {
            int l = 0, r = i - 1;
            while (l < r> {
                if (nums[l] + nums[r] > nums[i]) {
                    count += r - l;
                    --r;
                } else {
                    ++l;
                }
            }
        }
        return count;
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [2,2,3,4]

Output

x
+
cmd
3

#2 Code Example with Java Programming

Code - Java Programming


class Solution {
    public int triangleNumber(int[] nums) {
        Arrays.sort(nums);
        int count = 0;
        for (int i=0;i < nums.length-2;i++) {
            int k = i+2;
            for (int j=i+1;j < nums.length-1 && nums[i] != 0; j++) {
                while(k < nums.length && nums[k] < nums[i] + nums[j]) 
                    k++;
                count += k-j-1;
            }
        }
        
        return count;
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [2,2,3,4]

Output

x
+
cmd
3

#3 Code Example with Javascript Programming

Code - Javascript Programming


const triangleNumber = function(nums) {
  nums.sort((a, b) => a - b);
  let count = 0;
  let n = nums.length;
  for (let i = n - 1; i >= 2; i--) {
    let lo = 0;
    let mid = i - 1;
    while (lo  <  mid) {
      if (nums[lo] + nums[mid] > nums[i]) {
        count += mid - lo;
        mid -= 1;
      } else {
        lo += 1;
      }
    }
  }
  return count;
};

console.log(triangleNumber([2, 2, 3, 4]));
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [4,2,3,4]

Output

x
+
cmd
4
Advertisements

Demonstration


Previous
#609 Leetcode Find Duplicate File in System Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#617 Leetcode Merge Two Binary Trees Solution in C, C++, Java, JavaScript, Python, C# Leetcode