611. Valid Triangle Number

$O(n^2logn)$

AC Code

 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public:
    int triangleNumber(vector<int>& nums) {                
        sort(nums.begin(), nums.end());
        
        int n = nums.size();
        int cnt = 0;
        /* 
        a <= b <= c
        a + b > c
        */
        // iterate ab and search for c (upper bound -> l is the last element that is allowed)
        for(int i = 0; i < n; i++) {
            for(int j = i + 1; j < n; j++) {
                // a b c
                // a+b>c -> c<a+b=target
                
                // case 1
                // a...bvvvvvvvxxxxxxx
                //            lr
                // case 2
                // a...bxxxxxxxxxxxxxx
                //     lr
                // case 3
                // a...bvvvvvvvvvvvvvv
                //                   lr
                int left = j, right = n; // [left, right) -> both init to out of bound to cover case 2 and 3
                int target = nums[i] + nums[j];
                while(right - left > 1) {
                    int mid = (left + right) / 2;
                    
                    if(nums[mid] < target) {
                        left = mid;
                    } else {
                        right = mid;
                    }
                }
                
                if(left < n) {
                    cnt += left - j;
                }
            }
        }
        
        return cnt;
    }
};