Problem : https://leetcode.com/problems/valid-triangle-number/
To form a valid triangle, the 3 side lengths must compel with A + B > C.
Use binary search to find number of C which less than (A + B).
class Solution:
def triangleNumber(self, nums: List[int]) -> int:
nums.sort()
result = 0
for i in range(len(nums)):
for j in range(i+1, len(nums)-1):
k = bisect.bisect_left(nums, nums[i] + nums[j], j+1, len(nums))
result += k - (j+1)
return result
Java solution:
class Solution {
public int triangleNumber(int[] nums) {
Arrays.sort(nums);
int result = 0;
for (int i = 0; i < nums.length -1; i++) {
for (int j = i+1; j < nums.length - 1; j++) {
int k = lowerBound(nums, nums[i] + nums[j], j+1, nums.length);
result += k - (j+1);
}
}
return result;
}
/**
* Return position of the first number >= target
*/
int lowerBound(int[] nums, int target, int start, int end) {
int left = start;
int right = end;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > target)
right = mid;
else if (nums[mid] < target)
left = mid + 1;
else if (nums[mid] == target)
right = mid;
}
return right;
}
}
No comments:
Post a Comment