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出现的个数,比如如 ...
随机推荐
- TCP的状态 (SYN, FIN, ACK, PSH, RST, URG)
状态说明 SYN表示建立连接, FIN表示关闭连接, ACK表示响应, PSH表示有 DATA数据传输, RST表示连接重置. 其中,ACK是可能与SYN,FIN等同时使用的,比如SYN和ACK可能同 ...
- JavaEE学习文章汇总-并发,集群,分布式
以下文章来自博客 http://blog.csdn.net/FX_SKY/article/category/6203839 其中包括 集群Zookeeper 环境搭建 http://blog.csdn ...
- <form:select>的使用
最近在学习springMVC,用到了<form:select>标签,使用发过程中遇到了些问题,现在记录下,以防忘记. 我jsp页面是这样的: <%@ page language=&q ...
- 在javascript中使用Json
jSON是JavaScript面向对象语法的一个子集.由于JSON是JavaScript的一个子集,因此它可清晰的运用于此语言中. 文本生成json对象,必须在外面加一对括号. js 代码 var m ...
- java编码
/** * @Comments:default:ISO-8859-1 -> UTF-8 乱码则转码 * @param: str(乱码字符),coding(default:ISO- ...
- java 引用传递及基本应用
- History lives on in this distinguished Polish city 2017/1/4
原文 History lives on in this distinguished Polish city Though it may be ancient. KraKow, Poland, is a ...
- js正则匹配过滤 特殊字符
function stripscript(s) { var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<& ...
- Robot Framework 安装步骤
1. 安装python 2.7.11, 并添加环境变量到PATH.在cmd验证python是否安装成功. 2. 解压pip-8.1.1.tar.gz,执行python setup.py insta ...
- mysql定时任务
查看event是否开启: show variables like '%sche%'; 将事件计划开启: set global event_scheduler=1; 关闭事件任务: alter even ...