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出现的个数,比如如 ...
随机推荐
- Redis中connect与pconnect区别?
1.首先先介绍下connect和pconnect的区别. connect:脚本结束之后连接就释放了. 2.pconnect:脚本结束之后连接不释放,连接保持在php-fpm进程中. 所以使用pconn ...
- 一些常用的git指令
PyCharm编辑器 如何切换分支 git branch 查看当前在哪个分支,也会显示本地所有的分支名 git branch dev-chenqiao 新建分支 git checkout dev-ch ...
- Android Studio配置OpenCV(非NDK)
参考:http://www.cnblogs.com/tail/p/4618476.html 工具: 1,Android Studio(AS)1.4 2,Opencv 2.4.11 步骤: 1,解压下载 ...
- C#计算一段程序运行时间的三种方法
第一种方法利用System.DateTime.Now: static void SubTest() { DateTime beforDT = System.DateTime.Now; //耗时巨大的代 ...
- 设计向 20款优秀免费的Icons图标合集 (转)
Pioneer Icons Free Sample Sketch Resource Zodiac Icon Set Sketch Resource 90 Pixel Perfect Halloween ...
- CSS之div和span标签
div和span是非常重要的标签,div的语义是division"分割": span的语义就是span"范围.跨度". 这两个东西,都是最最重要的"盒 ...
- AngularJS版本下载
大家可以从下面地址获取AngularJS所以版本: https://code.angularjs.org/
- Java中堆的实现类PriorityQueue队列接口Queue
Application:这层的职责是对接收到的数据做一些非业务性验证,事务的控制,最重要的是协调多个聚合之间的操作.这里应该可以清晰的表达出整个操作所做的事情,并且与通用语言是一致的. 以上我们讲到可 ...
- MVC POST在ACTION上进行多个模型的数据绑定
首先声明,接下来的东西并不符合本人认同的严谨的MVC模式. 用MVC做项目的过程中,越来越多的用到不严谨的MVC编程. 比如,在"cshtml"文件中写: @Html.Raw(DB ...
- UUID库
If you cannot afford to use Boost, then there is a very minimal library that I implemented which sim ...