zoukankan      html  css  js  c++  java
  • [leetcode]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].

    题意:

    给定数组,可由数组中的数字组成多少个valid三角形

    解本题的背景知识: 【Math fact】The sum of two sides of a triangle must be greater than the third one

    Solution1: Two Pointers (similar as 3 Sum problem)

    1. sort array

    2. lock pointer k at the trail (must be largest side)

    3. set pointer left at 0, right at k-1.    Lock pointer k and pointer right

         

    check if nums[left] + nums[right] > nums[k]  

             (1)YES.  Then we can say  (nums[left + 1] / nums[left + 2]....) + nums[right] > nums[k]

                                

                             So combination count: right - left

                             Then lock pointer k and pointer right -1 to get next combination count

                (2) No.   Then left ++

    code

     1 /*
     2 Time: O(n^2)
     3 Space: O(1)
     4 */
     5 
     6 class Solution {
     7     public int triangleNumber(int[] nums) {
     8         if(nums == null || nums.length == 0) return 0;
     9         Arrays.sort(nums);  
    10         int result = 0;
    11          for (int k = nums.length - 1; k > 0 ; k--) {
    12             int left = 0;
    13             int right = k - 1 ;
    14             while (left < right) {
    15                 if (nums[left] + nums[right] > nums[k]) {
    16                     result += (right - left);
    17                     right--;
    18                 }
    19                 else {
    20                     left++;
    21                 }
    22             }
    23         } 
    24         return result;
    25     }
    26 }

                              

  • 相关阅读:
    python之定时器Timer
    (转载)Python一篇学会多线程
    docker速记
    IP地址简单入门
    pycharm快捷键及一些常用设置(转载)
    python系列1_travel
    Fluter基础巩固之Dart语言详解<三>
    Fluter基础巩固之Dart语言详解<二>
    Fluter基础巩固之Dart语言详解<一>
    Java精通并发-Condition编程模式详解与分析
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10807456.html
Copyright © 2011-2022 走看看