Leetcode611. Valid Triangle Number
题目
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.
Example:
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
解题分析
这道题其实不难,只要你理清了解题的思路。题目的要求很明确,就是让我们计算数组中可以构成三角形的数目。我们都知道,要想构成三角形,只需三角形中两条最短边之和大于最长边即可。
基于这样的原理,我们可以先将数组从小到大进行排序。将数组排序后,我们可以这样想,固定某一个数,然后用左右两个指针分别指向某个数,当左右指针指向的数字之和大于我们固定的数时,说明此种情况成立。然后将右指针向左移动一位继续判断直到不满足为止,将左指针向右移动一位继续判断;直到左指针跟右指针重合。
根据这个思路,我们将数组从大到小遍历,将当前遍历的数nums[i]进行固定,让左指针指向第0个数nums[0],右指针指向这个数的左边一个数nums[i-1]。当nums[left]+nums[right]>nums[i]时,把右指针right固定,可以想到:当左指针left往右遍历时,左指针与右指针之间的和肯定也满足要求;因此有count+=(right-left)。
将右指针right往左移一位,继续进行判断,如果成立,则right继续重复前面操作;如果不成立,说明两个数之和太小了,此时将左指针left往右移一位,继续进行判断,直到left与right指针重合,这样就把nums[i]所有的情况都考虑了,最后数组遍历完结果就出来了,是不是很简单呢?
源代码
class Solution {
public:
int triangleNumber(vector<int>& nums) {
int count = 0, size = nums.size();
sort(nums.begin(), nums.end());
for (int i = size - 1; i >= 2; i--) {
int left = 0, right = i - 1;
while(left < right) {
if (nums[left] + nums[right] > nums[i]) {
count += (right - left);
right--;
}
else {
left++;
}
}
}
return count;
}
};
以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~