611. Number of Valid Triangles
611. The number of valid triangles https://leetcode.cn/problems/valid-triangle-number/
Title description:
Given an array of non-negative integers nums
, return the number of triples that can form the sides of a triangle.
Problem-solving ideas:
This question is a question about whether a triangle can be established. First, we assume that the three sides of the triangle (a, b, c), we must ensure that the sum of the two sides is greater than the third side
The title gives us that nums are out of order. If we experiment with abc one by one, it will time out (time complexity O^3)
When we sort the sort, so assuming that a<b<c, we only need to judge whether a+b>c is true!
Here we traverse each c (from back to front), so that the time complexity becomes N^2+NlogN, which is N^2
Problem-solving code:
class Solution {
public:
int triangleNumber(vector<int>& nums) {
sort(nums.begin(),nums.end());
//假设a<b<c
int num=0;
int n=nums.size();
for(int i=n-1;i>=2;i--)
{
int left=0;
int right=i-1;
while(left<right)
{
if(nums[left]+nums[right]>nums[i])
{
num+=(right-left);
right--;
}
else
{
left++;
}
}
}
return num;
}
};
Sword refers to Offer 57. Two numbers whose sum is s
Title description:
Input an array sorted in ascending order and a number s, find two numbers in the array such that their sum is exactly s. If the sum of multiple pairs of numbers is equal to s, just output any pair.
Problem-solving ideas:
First of all, this question is an ascending array. If we use violence here, it will time out
Here we use double pointers, we let one point to the head left and one point to the tail right, here there will be three relationships between left, right and target
We assume sub=right-left
In the first case, it is obvious to return directly. Let's study the second and third cases:
Problem-solving code:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n=nums.size();
int left=0;
int right=n-1;
while(nums[right]>target)
{
right--;
}
while(left<right)
{
int sub=target-nums[right];
if(sub==nums[left])
{
return {nums[left],nums[right]};
}
else if(sub>nums[left])
{
left++;
}
else//sub<nums[left]
{
right--;
}
}
return {-1,-1};
}
};