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 The Triangle Inequality Theorem states that the sum of any 2 sides of a triangle must be greater than the measure of the third side. // solution 1 : class Solution { public int triangleNumber(int[] nums) { // 219 / 220 test cases passed. // tle , time : n ^ 3 // brute force solution: try all possible combination of any three numbers // check if its valid , int res = 0; for(int i = 0; i < nums.length - 2; i++){ for(int j = i + 1; j < nums.length - 1; j++){ for(int k = j + 1; k < nums.length; k++){ int a = nums[i], b = nums[j], c = nums[k]; if(a + b > c && b + c > a && a + c > b) res++; } } } return res; } } // solution 2 https://www.youtube.com/watch?v=bojX9bdra-w Sort it first Greedy: use math tricks to avoid trying all possible solutions , still guarantee the correctness of the result ?? How to guarantee that a + b > c Also means a + c > b and b + c > a , if only one ineuqkaity is valid and we change b to d , how to ensure the other two are also valid ?? class Solution { public int triangleNumber(int[] nums) { Arrays.sort(nums); // use some space or tricks to trade time (binary search) // what's some inefficeincy about this algorithms int res = 0; for(int i = nums.length - 1; i >= 2; i--){ // fix i int l = 0; int r = i - 1; while(l < r){ if(nums[l] + nums[r] > nums[i]){ res += r - l ; // r--; // fix one r , try all possible l }else{ // nums[l] + nums[r] <= nums[i] // need to move l to the right l++; } } } return res; } }
posted on 2018-11-09 10:19 猪猪🐷 阅读(99) 评论(0) 收藏 举报
浙公网安备 33010602011771号