LeetCode Valid Triangle Number

原题链接在这里:https://leetcode.com/problems/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 1:

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

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].

题解:

也是Two Pointers, 构成三角要求三条边成a + b > c. 设nums[i] 为c, 前面的数中选出nums[l]为a, nums[r]为b.

若是nums[l] + nums[r] > c则符合要求,若继续向右移动l, 有r-l种组合都包括num[r]. 所以res += r-l. r左移一位, 之后可能还有符合条件的组合.

若是nums[l] + nums[r] <= c, 则向右移动l.

Time Complexity: O(n^2). sort 用时O(nlogn), 对于每一个c, Two Points用时O(n). n = nums.length.

Space: O(1).

AC Java:

 class Solution {
public int triangleNumber(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
} int res = 0;
Arrays.sort(nums);
for(int i = 2; i<nums.length; i++){
int l = 0;
int r = i-1;
while(l<r){
if(nums[l] + nums[r] > nums[i]){
res += r-l;
r--;
}else{
l++;
}
}
}
return res;
}
}

类似3Sum Smaller.

上一篇:[CLR via C#]4. 类型基础及类型、对象、栈和堆运行时的相互联系


下一篇:COJN 0584 800603吃糖果