当前位置:网站首页>Summary of most consistency problems
Summary of most consistency problems
2022-07-25 10:12:00 【weixin_ forty-six million two hundred and thirteen thousand one】
Catalog
167. Sum of two numbers II - Input an ordered array
653. Sum of two numbers IV - Input BST
713. The product is less than K Subarray
1. Sum of two numbers
Given an array of integers nums And an integer target value target, Please find... In the array And is the target value target the Two Integers , And return their array subscripts .
You can assume that each input corresponds to only one answer . however , The same element in the array cannot be repeated in the answer .
You can return the answers in any order .
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map <int,int> map;
for(int i = 0; i < nums.size(); i++) {
auto iter = map.find(target - nums[i]);
if(iter != map.end()) {
return {iter->second, i};
}
map.insert(pair<int, int>(nums[i], i));
}
return {};
}
};167. Sum of two numbers II - Input an ordered array
I'll give you a subscript from 1 The starting array of integers numbers , The array has been pressed Non decreasing order , Please find out from the array that the sum satisfying the addition is equal to the target number target Two numbers of . Let these two numbers be numbers[index1] and numbers[index2] , be 1 <= index1 < index2 <= numbers.length .
In length 2 Array of integers for [index1, index2] Returns the subscript of these two integers in the form of index1 and index2.
You can assume that each input Only corresponding to the only answer , And you Can not be Reuse the same elements .
The solution you design must use only constant level extra space .
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> res;
int l=0,r=numbers.size()-1;
while(true){
int sum=numbers[l]+numbers[r];
if(sum==target) {
res.push_back(l+1);
res.push_back(r+1);
break;
}
else if(sum>target){
r--;
}
else l++;
}
return res;
}
};653. Sum of two numbers IV - Input BST
Given a binary search tree root And a target result k, If BST There are two elements in and their sum is equal to the given target result , Then return to true.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_set<int> set;
bool findTarget(TreeNode* root, int k) {
if(root==nullptr) return false;
if(set.count(k-root->val)) return true;
else set.insert(root->val);
return findTarget(root->left,k)||findTarget(root->right,k);
}
};560. And for K Subarray
Give you an array of integers nums And an integer k , Please count and return The array is k The number of consecutive subarrays of .
The prefix and
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> mp;
mp[0] = 1;
int count = 0, pre = 0;
for(int i=0;i<nums.size();i++){
pre+=nums[i];
if(mp.count(pre-k)){
count+=mp[pre-k];
}
mp[pre]++;
}
return count;
}
};523. Continuous subarrays and
( Not fully mastered )
Give you an array of integers nums And an integer k , Write a function to determine whether the array contains continuous subarrays that meet the following conditions at the same time :
Subarray size At least for 2 , And
The sum of subarray elements is k Multiple .
If there is , return true ; otherwise , return false .
If there is an integer n , Make integer x accord with x = n * k , said x yes k A multiple of .0 Always regarded as k A multiple of .
【 Congruence theorem 】 【 Hashtable 】【 Simplify prefixes and 】
Congruence theorem : If two integers m、n Satisfy n-m Can be k to be divisible by , that n and m Yes k congruence
namely ( pre(j) - pre (i) ) % k == 0 be pre(j) % k == pre(i) % k
deduction => pre (i) % k = (a0 + a1 + ... + ai) % k = (a0 % k + a1 % k + ... ai % k ) % k ( This derivation is useful in simplifying prefixes and , State the current prefix and % k It will not affect the following prefixes and % k )
Hashtable Storage Key :pre(i) % k
Value: i
Ergodic process :
Calculate the prefix and pre( j ) % k
When pre(j) % k Already exists in the hash table , It means that there is i Satisfy pre(j) % k == pre(i) % k ( i < j )
HashMap in , It is known that Key, You can get it. Value namely i Value , Last Judge j - i >= 2 Is it true that will do
3. When pre(j) % k Does not exist in the hash table , Will (pre(j) % k, j ) Save to hash table
class Solution {
public:
unordered_map<int,int> map;
bool checkSubarraySum(vector<int>& nums, int k) {
if(nums.size()<2) return false;
for(int i=1;i<nums.size();i++){
nums[i]+=nums[i-1];// The prefix and
}
map[0]=-1;// initialization Prefixes and are 0 The subscript of is -1 non-existent
for(int i=0;i<nums.size();i++){
int temp=nums[i]%k;
// if(temp==0) return true;
if(map.count(temp)) {
int preindex=map[temp];
if(i-preindex>=2) return true;
}
else map[temp]=i;
}
return false;
}
};713. The product is less than K Subarray
Give you an array of integers nums And an integer k , Please return that the product of all elements in the subarray is strictly less than k The number of consecutive subarrays of .
Example 1:
Input :nums = [10,5,2,6], k = 100
Output :8
explain :8 The product is less than 100 The subarrays of are :[10]、[5]、[2],、[6]、[10,5]、[5,2]、[2,6]、[5,2,6].
It should be noted that [10,5,2] It's not that the product is less than 100 Subarray .
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
int n = nums.size(), ret = 0;
int prod = 1;
int left=0;
for(int right=0;right<nums.size();right++){// The right pointer traverses from left to right
prod*=nums[right];// Calculate the sum of the products in the sliding window
while(left<=right&&prod>=k){
prod/=nums[left++];// The sum of prefix products is greater than or equal to k Move the left pointer to the right And remove the current element of the left pointer
}
ret+=right-left+1;// The number of subarrays in the sliding window
}
return ret;
}
};152. Product maximum subarray
Give you an array of integers nums , Please find the non empty continuous subarray with the largest product in the array ( The subarray contains at least one number ), And returns the product of the subarray .
The answer to the test case is 32- position Integers .
Subarray Is a continuous subsequence of an array .
class Solution {
public:
int maxProduct(vector<int>& nums) {
int maxF = nums[0], minF = nums[0], ans = nums[0];
for (int i = 1; i < nums.size(); ++i) {
// Maximum and minimum values before storage
int mx=maxF;
int mn=minF;
maxF=max(maxF*nums[i],max(nums[i],mn*nums[i]));// Similar to dynamic planning
minF=min(minF*nums[i],min(nums[i],mx*nums[i]));
ans = max(maxF, ans);
}
return ans;
}
};15. Sum of three numbers
Give you one containing n Array of integers nums, Judge nums Are there three elements in a,b,c , bring a + b + c = 0 ? Please find out all and for 0 Triple without repetition .
Be careful : Answer cannot contain duplicate triples .
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> result;
for(int i=0;i<nums.size();i++){
if (i > 0 && nums[i] == nums[i-1]) continue;// duplicate removal Otherwise, there will be repeated solutions
int left=i+1;
int right=nums.size()-1;
while(left<right){
if(nums[left]+nums[right]>-nums[i]) right--;
else if(nums[left]+nums[right]<-nums[i]) left++;
else{
result.push_back({nums[i],nums[left],nums[right]});
left++;
right--;
// After finding the solution same left and right No more use Need to be heavy while loop
while(left<right&&nums[left]==nums[left-1]) left++;
while(left<right&&nums[right]==nums[right+1]) right--;
}
}
}
return result;
}
};16. The closest sum of three
Give you a length of n Array of integers for nums and A target value target. Please start from nums Choose three integers , Make their sum with target Nearest .
Returns the sum of the three numbers .
It is assumed that there is only exactly one solution for each set of inputs .
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int n = nums.size();
int best = 1e8;
for(int i=0;i<nums.size();i++){
int left=i+1;
int right=nums.size()-1;
if(i>0&&nums[i]==nums[i-1]) continue;
while(left<right){
int sum=nums[left]+nums[right]+nums[i];
if(sum==target) return sum;
if(abs(sum-target)<abs(best-target)){
best=sum;
}
if(sum>target){
right--;
while(left<right&&nums[right]==nums[right+1]) right--;
}
if(sum<target){
left++;
while(left<right&&nums[left]==nums[left-1]) left++;
}
}
}
return best;
}
};18. Sum of four numbers
Here you are n An array of integers nums , And a target value target . Please find and return the quads that meet all the following conditions and are not repeated [nums[a], nums[b], nums[c], nums[d]] ( If two Quad elements correspond to each other , It is considered that two quads repeat ):
0 <= a, b, c, d < n
a、b、c and d Different from each other
nums[a] + nums[b] + nums[c] + nums[d] == target
You can press In any order Return to the answer .
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();i++){
if(i>0&&nums[i]==nums[i-1]) continue;
for(int j=i+1;j<nums.size();j++){
if(j>i+1&&nums[j]==nums[j-1]) continue;
int left=j+1;
int right=nums.size()-1;
while(left<right){// There has to be this while loop
long int temp=nums[i]+nums[j];
if((long)nums[right]+nums[left]>target-temp){
right--;
}
else if((long)nums[right]+nums[left]<target-temp){
left++;
}
else {
result.push_back({nums[i],nums[j],nums[left],nums[right]});
right--;
left++;
while(left<right&&nums[left]==nums[left-1]) left++;
while(left<right&&nums[right]==nums[right+1]) right--;
}
}
}
}
return result;
}
};454. Add four numbers II
Here are four integer arrays nums1、nums2、nums3 and nums4 , The length of the array is n , Please calculate how many tuples there are (i, j, k, l) To meet the :
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int, int> umap; //key:a+b The numerical ,value:a+b The number of times the value appears
// Ergodic large A And big B Array , Count the sum of two array elements , And the number of times , Put it in map in
for (int a : A) {
for (int b : B) {
umap[a + b]++;
}
}
int count = 0; // Statistics a+b+c+d = 0 Number of occurrences
// In ergodic big C And big D Array , Find out if 0-(c+d) stay map If you've seen it in the past , Just put map in key Corresponding value That is, the number of occurrences .
for (int c : C) {
for (int d : D) {
if (umap.find(0 - (c + d)) != umap.end()) {
count += umap[0 - (c + d)];
}
}
}
return count;
}
};边栏推荐
猜你喜欢

CCF 201503-4 network delay

阿里MQTT物联网平台“云产品流转”实战——两片ESP32通过物联网平台实现远程互操作

¥ 1-1 SWUST OJ 941: implementation of consolidation operation of ordered sequence table
![[recommended collection] with these learning methods, I joined the world's top 500 - the](/img/95/e34473a1628521d4b07e56877fcff1.png)
[recommended collection] with these learning methods, I joined the world's top 500 - the "fantastic skills and extravagance" in the Internet age

¥ 1-2 example 2.2 put the union of two sets into the linear table

用ESP32+TM1638实验NTP网络校时闹钟的ARDUINO代码

看一个双非二本(0实习)大三学生如何拿到阿里、腾讯的offer

小程序企业发放红包功能

Probability theory and mathematical statistics 4 continuous random variables and probability distributions (Part 1)
![[RNN] analyze the RNN from rnn- (simple|lstm) to sequence generation, and then to seq2seq framework (encoder decoder, or seq2seq)](/img/6e/da80133e05b18c87d7167c023b6c93.gif)
[RNN] analyze the RNN from rnn- (simple|lstm) to sequence generation, and then to seq2seq framework (encoder decoder, or seq2seq)
随机推荐
@Import,Conditional和@ImportResourse注解
An ASP code that can return to the previous page and automatically refresh the page
用ESP32+TM1638实验NTP网络校时闹钟的ARDUINO代码
VScode配置ROS开发环境:修改代码不生效问题原因及解决方法
Mlx90640 infrared thermal imaging sensor temperature measurement module development notes (II)
Fundamentals of C language
Mlx90640 infrared thermal imager temperature measurement module development instructions
用Arduino写个ESP32看门狗
工程监测多通道振弦传感器无线采集仪外接数字传感器过程
小程序企业发放红包功能
Detailed explanation of MySQL database
Eco introduction
@5-1 CCF 2019-12-1 reporting
Probability theory and mathematical statistics 4 continuous random variables and probability distributions (Part 1)
framework打包合并脚本
SSM integration (simple library management system to integrate SSM)
Data viewing and parameter modification of multi-channel vibrating wire, temperature and analog sensing signal acquisition instrument
mysql历史数据补充新数据
message from server: “Host ‘xxx.xxx.xxx.xxx‘ is not allowed to connect to this MySQL server“
Introduction to armv8 architecture