zoukankan      html  css  js  c++  java
  • Triangle Count

    Given an array of integers, how many three numbers can be found in the array, so that we can build an triangle whose three edges length is the three numbers that we find?

    Example

    Given array S = [3,4,6,7], return 3. They are:

    [3,4,6]
    [3,6,7]
    [4,6,7]
    

    Given array S = [4,4,4,4], return 4. They are:

    [4(1),4(2),4(3)]
    [4(1),4(2),4(4)]
    [4(1),4(3),4(4)]
    [4(2),4(3),4(4)]
    

    先sort 然后对于每一个元素i 利用左右双index扫面0到i-1 找出符合条件的元素对

     1 public class Solution {
     2     /**
     3      * @param S: A list of integers
     4      * @return: An integer
     5      */
     6     public int triangleCount(int S[]) {
     7         Arrays.sort(S);
     8         int count = 0;
     9         for (int i = 0; i < S.length; i++) {
    10             int left = 0;
    11             int right = i - 1;
    12             while (left < right) {
    13                 if (S[left] + S[right] > S[i]) {
    14                     // The edge from S[left] to S[right - 1] will also form a triangle
    15                     count += right - left;
    16                     right--;
    17                 } else {
    18                     left++;
    19                 }
    20             }
    21         }
    22         return count;
    23     }
    24 }
  • 相关阅读:
    软件质量见解
    Vim 简明教程【转载】
    Actor Mailbox
    Unity对齐工具
    静态AOP Fody PropertyChanged
    棋牌分布式架构
    死锁
    curl 获取自定义数据
    WPF RichTextBox添加一条有颜色的记录
    arp -s 添加失败:拒绝访问
  • 原文地址:https://www.cnblogs.com/xinqiwm2010/p/6836202.html
Copyright © 2011-2022 走看看