Saturday, July 22, 2017

[Leetcode] Valid Triangle Number, Solution

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].

[Thoughts]

[Code]
``````1:    int triangleNumber(vector<int>& nums) {
2:      if(nums.size() < 3) return 0;
3:
4:      sort(nums.begin(), nums.end());
5:
6:      int count = 0;
7:      for(int third_edge =2; third_edge < nums.size(); third_edge++) {
8:        int first_edge = 0, second_edge = third_edge-1;
9:        while(first_edge < second_edge) {
10:          if(nums[first_edge] + nums[second_edge] > nums[third_edge]) {
11:            count+= second_edge - first_edge;
12:            second_edge --;
13:          }else {
14:            first_edge ++;
15:          }
16:        }
17:      }
18:      return count;
19:    }
``````