• 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 }
  • 相关阅读:
    C#泛型
    Chrome 中调试Javascript
    Oracle分页查询语句
    WordCount2.2
    第一周博客作业
    WordCount--统计输入文件的字符数、行数、单词数(java)--初级功能
    PHP数据库操作
    PHP安全函数
    PHP基础
    用户/目录操作
  • 原文地址:https://www.cnblogs.com/xinqiwm2010/p/6836202.html
Copyright © 2020-2023  润新知