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出现的个数,比如如 ...
随机推荐
- ImportError: cannot import name '_imagingtk'
问题描述 使用tkinter画pillow生成的图片时,在tkinter中抛出此异常. 解决方案 pip install -I --no-cache-dir Pillow 更新pillow 重启解决一 ...
- JSP中编译指令include与动作指令include的区别
include指令是编译阶段的指令,即include所包含的文件的内容是编译的时候插入到JSP文件中,JSP引擎在判断JSP页面未被修改, 否则视为已被修改.由于被包含的文件是在编译时才插入的,因此如 ...
- redis 命令
添加数据 p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo } span.s1 { } set key value //添加多条数据 ...
- 输入流和字符串互转,InputStream2String,String2InputStream
输入流转字符串 public static String InputStream2String(InputStream in) { InputStreamReader reader = null; t ...
- ContextFlyout 在10586或10240的使用
虽然ContextFlyout只能在红石以上版本使用,但可以采用附加属性的方法手动写一个 public static class ContextFlyoutSetter { public static ...
- time step和采样频率的关系
当前的采样频率为11025HZ,overlap=0.5,取的是1024个采样点为1帧.则time step为256时的时间长度为11秒.即以11秒为单位分割原始的音频,生成一张语普图. >> ...
- IIS请求筛选模块被配置为拒绝超过请求内容长度的请求
HTTP错误404.13 - Not Found 请求筛选模块被配置为拒绝超过请求内容长度的请求,原因是Web服务器上的请求筛选被配置为拒绝该请求,因为内容长度超过配置的值(IIS 7 默认文件上传大 ...
- UP board 漫谈(1)——从Atom到UP Board
title: UP board 漫谈(1)--从Atom到UP Board date: 2016-12-26 12:33:03 tags: UP board categories: 开发板 perma ...
- 深入理解JSX
本文由笔者翻译自官方文档的JSX In Depth,若干案例经过了改写.其实说白了也好像不算太深入,但还是提示了一些可能的盲区. JSX是为构造React元素方法React.createElement ...
- php ob_flush 和flush
“ob_flush()和flush()的区别.前者是把数据从PHP的缓冲中释放出来,后者是把不在缓冲中的或者说是被释放出来的数据发送到浏览器.所以当缓冲存在的时候,我们必须ob_flush()和flu ...