Leetcode之Valid Triangle Number 问题

来源:互联网 发布:百度软件中心开发者 编辑:程序博客网 时间:2024/06/06 03:22

问题描述:

Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.

Note:

  1. The length of the given array won't exceed 1000.
  2. The integers in the given array are in the range of [0, 1000].

示例:

Input: [2,2,3,4]
Output: 3
Explanation:
Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3

问题来源:Valid Triangle Number (详细地址:https://leetcode.com/problems/valid-triangle-number/description/)

思路分析:题目的意思就是要找到三个能构成三角行的三个数,题目中的示例已经给出了一部分提示,数组必须是排好序的。所以我们先调用库函数sort()方法先排好序,接着我们启动三个指针:一个i作为遍历指针;一个low每次都从0开始,从左往右遍历;一个high每次都从i前面的一个位置出发,从右往左遍历。每次固定住i指针,我们比较nums[low] + nums[high]的大小和nums[i]的大小关系,既然是比较大小,那就有三种关系:

1.)nums[low] + nums[high] < nums[i],说明二者之和还是太小,那么我们的low指针就往右移动,即low++;

2.)nums[low] + nums[high] = nums[i],往常的思路这里就找到答案了,但是两边之和等于第三边能构成三角形吗?显然不行,所以和1.)是一个情形,low++;

3.)nums[low] + nums[high] > nums[i],这是我们希望看到的结果,但是结果应该是多少呢?其实位于low和high之间的元素都是成立的,为什么呢?你固定住high,想想low指向的数都满足条件,low右边的数还不能满足吗?这种情况i也要往左走了,因为i位于该位置的正确答案了啊。

代码:




原创粉丝点击