zoukankan      html  css  js  c++  java
  • 【Lintcode】382.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)]

    题解:

      此类题目首先想到的是数组先排序(数组元素位置不影响结果,且题目与元素大小有关),最简单的是暴力搜索,三层循环。首先k从 2 遍历到 length(S)-1,内循环则为i和j枚举满足条件的情况。这里有个小技巧,因为我们首先对数组进行排序(从小到大),如例1,当S[k] = 7 时, i初始化为0,j初始化为k-1,那么有S[i] + S[j] > S[k],此时不需要再检查4+6>7的情况,因为3已经满足条件了,那么3以后的元素肯定也满足。这样就会减少大量的运算时间。一次遍历即可。

    Solution 1 

    class Solution {
    public:
        int triangleCount(vector<int> &S) {
            int ans = 0;
            int len = S.size();
            if (len < 3) {
                return 0;
            }
            sort(S.begin(), S.end());
            for (int k = 2; k < len; ++k) {
                int i = 0; 
                int j = k - 1;
                while (i < j) {
                    if (S[i] + S[j] > S[k]) {
                        ans += j - i;
                        j--;
                    } else {
                        i++;
                    }
                }
            }
            return ans;
        }
    };
  • 相关阅读:
    css样式2 布局 定位 层级 显示
    css与样式
    表单属性、键值对
    表单
    列表、表格
    实体、颜色、路径、标签、超链接、图片
    2018/07/05 html基础
    TP 链接数据库与Model模型的创建
    ThinkPHP 模板循环语法
    tp 单字母函数详解(摘自网络)
  • 原文地址:https://www.cnblogs.com/Atanisi/p/7003567.html
Copyright © 2011-2022 走看看