题目
代码
方法1,暴力法:(时间超时)
class Solution {
public int triangleNumber(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length - 2; i++) {
for (int j = i + 1; j < nums.length -1; j++) {
for (int k = j + 1; k < nums.length; k++) {
if (nums[i] + nums[j] > nums[k] && nums[k] + nums[j] > nums[i] &&nums[i] + nums[k] > nums[j]){
count++;
}
}
}
}
return count;
}
}
方法2,双指针法:
class Solution {
public int triangleNumber(int[] nums) {
int count = 0;
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
int k = i + 2;
for (int j = i + 1; j < nums.length - 1 && nums[i] != 0; j++) {
while (k < nums.length && nums[j] + nums[i] > nums[k])
k++;
count = count + k - j -1;
}
}
return count;
}
}