Count the number of possible triangles
From: http://www.geeksforgeeks.org/find-number-of-triangles-possible/
Given an unsorted array of positive integers. Find the number of triangles that can be formed with three different array elements as three sides of triangles. For a triangle to be possible from 3 values, the sum of any two values (or sides) must be greater than the third value (or third side).
For example, if the input array is {4, 6, 3, 7}, the output should be 3. There are three triangles possible {3, 4, 6}, {4, 6, 7} and {3, 6, 7}. Note that {3, 4, 7} is not a possible triangle.
As another example, consider the array {10, 21, 22, 100, 101, 200, 300}. There can be 6 possible triangles: {10, 21, 22}, {21, 100, 101}, {22, 100, 101}, {10, 100, 101}, {100, 101, 200} and {101, 200, 300}
Method 1 (Brute force)
The brute force method is to run three loops and keep track of the number of triangles possible so far. The three loops select three different values from array, the innermost loop checks for the triangle property ( the sum of any two sides must be greater than the value of third side).
Time Complexity: O(N^3) where N is the size of input array.
Method 2 (Tricky and Efficient)
Let a, b and c be three sides. The below condition must hold for a triangle (Sum of two sides is greater than the third side)
i) a + b > c
ii) b + c > a
iii) a + c > b
Following are steps to count triangle.
1. Sort the array in non-decreasing order.
2. Initialize two pointers ‘i’ and ‘j’ to first and second elements respectively, and initialize count of triangles as 0.
3. Fix ‘i’ and ‘j’ and find the rightmost index ‘k’ (or largest ‘arr[k]’) such that ‘arr[i] + arr[j] > arr[k]’. The number of triangles that can be formed with ‘arr[i]’ and ‘arr[j]’ as two sides is ‘k – j’. Add ‘k – j’ to count of triangles.
Let us consider ‘arr[i]’ as ‘a’, ‘arr[j]’ as b and all elements between ‘arr[j+1]’ and ‘arr[k]’ as ‘c’. The above mentioned conditions (ii) and (iii) are satisfied because ‘arr[i] < arr[j] < arr[k]'. And we check for condition (i) when we pick 'k'4. Increment ‘j’ to fix the second element again.
Note that in step 3, we can use the previous value of ‘k’. The reason is simple, if we know that the value of ‘arr[i] + arr[j-1]’ is greater than ‘arr[k]’, then we can say ‘arr[i] + arr[j]’ will also be greater than ‘arr[k]’, because the array is sorted in increasing order.
5. If ‘j’ has reached end, then increment ‘i’. Initialize ‘j’ as ‘i + 1’, ‘k’ as ‘i+2’ and repeat the steps 3 and 4.
Following is implementation of the above approach.
class CountTriangles {
public int findNumberOfTriangles(int arr[]) { int n = arr.length, count = ;
Arrays.sort(arr); for (int i = ; i < n-; ++i) {
int k = i + ; for (int j = i+; j < n; ++j) {
while (k < n && arr[i] + arr[j] > arr[k]) {
++k;
}
count += k - j - ;
}
}
return count;
}
}
Count the number of possible triangles的更多相关文章
- [geeksforgeeks] Count the number of occurrences in a sorted array
Count the number of occurrences in a sorted array Given a sorted array arr[] and a number x, write a ...
- How to count the number of threads in a process on Linux
If you want to see the number of threads per process in Linux environments, there are several ways t ...
- 2017年上海金马五校程序设计竞赛:Problem C : Count the Number (模拟)
Description Given n numbers, your task is to insert '+' or '-' in front of each number to construct ...
- OpenCV count the number of connected camera 检测连接的摄像头的数量
有时候在项目中我们需要检测当前连接在机子上的摄像头的数量,可以通过下面的代码实现,其中连接摄像头的最大数量maxCamNum可以任意修改: /** * Count current camera num ...
- 1. 青蛙跳跳FrogJmp Count minimal number of jumps from position X to Y.
青蛙跳跳: package com.code; public class Test03_1 { public int solution(int X, int Y, int D) { int res = ...
- fatal error C1003: error count exceeds number; stopping compilation解决方法
[error]C1003: error count exceeds 100; stopping compilation ...winnt.h 在项目工程中添加#include<windows.h ...
- FB面经prepare: Count the number of Vector
给一个超级大的排好序的vector [abbcccdddeeee]比如,要求返回[{,a}, {,b}, {,c}, {,d}, {,e}......]复杂度要优于O(N) 分析: 如果是binary ...
- Codeforces Round #249 (Div. 2) D. Special Grid 枚举
题目链接: http://codeforces.com/contest/435/problem/D D. Special Grid time limit per test:4 secondsmemor ...
- [CareerCup] 18.4 Count Number of Two 统计数字2的个数
18.4 Write a method to count the number of 2s between 0 and n. 这道题给了我们一个整数n,让我们求[0,n]区间内所有2出现的个数,比如如 ...
随机推荐
- 51nod 最小周长
1283 最小周长 题目来源: Codility 基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题 收藏 关注 一个矩形的面积为S,已知该矩形的边长都是整数,求所有 ...
- 【前端积累】JavascriptUtil 字符串部分
//计算字符串长度 String.prototype.strLen = function() { var len = 0; for (var i = 0; i < this.length; i+ ...
- javaWeb实现登录功能
1.三要素 (1) 入口 就是我们所在的页面 入口到处理的数据请求会出现乱码,用request.SetCharacterEncoding("UTF-8");来解决,仅仅是用用于Po ...
- ISO
- 关于pc端直播
写这篇文章首先是想给自己一个总结.整理,还有就是给那些 没有特别明白直播是怎么回事的人一点 思路 最近公司想要做pc端直播,作为一个自认为很菜的前端实在是不知从何下手,所以只能用国人最爱的百度,搜索了 ...
- QQ,微信第三方登陆
感觉越是大公司的SDK越不好用,其实我也是一直在想为什么他们拿那么高的工资却干着不相应的事儿. 下面说下QQ和微信第三方登陆的一点坑 首先 (QQ互联)自带的sdk中 一个文件工程没有调用产生关联错 ...
- Sql的decimal、float、double类型的区别
三者的区别介绍 float:浮点型,含字节数为4,32bit,数值范围为-3.4E38~3.4E38(7个有效位) double:双精度实型,含字节数为8,64bit数值范围-1.7E308~1.7E ...
- wxpython绘制折线图
environment:win10 + eclipse + pydev + python2.7.11 + wxpython3.0.2 code sample: #!/usr/bin/env pytho ...
- 继承 原生js 与 $.extend(true,default,opts||{});
$.extend(true,default,opts||{}); var obj1={ name:'liu', sex:'m', work:'pc' } var obj2={ sex:'w' } va ...
- github教程
http://www.yangzhiping.com/tech/github.html