2022.7.5

1.逆向双指针,把值大的排到nums1的尾部,省去了创建新数组的空间。

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int a=m-1,b=n-1;
        int e=m+n-1;
        int cur;
        while(a>=0 || b>=0){
            if(a<0){
                cur=nums2[b];
                b--;
            }
            else if(b<0){
                cur=nums1[a];
                a--;
            }
            else if(nums1[a]<=nums2[b]){
                cur=nums2[b];
                b--;
            }
            else{
                cur=nums1[a];
                a--;
            }
            nums1[e]=cur;
            e--;
        }

    }
};

在这里插入图片描述
2.快慢指针,若是有环,一定会相遇。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
    if(head==nullptr || head->next==nullptr){
        return false;
    }
    ListNode * slow=head;
    ListNode * fast=head->next;
    while(fast!=slow){
        if(fast==nullptr || fast->next==nullptr){
            return false;
        }
        fast=fast->next->next;
        slow=slow->next;
    }
    return true;
    }
};

在这里插入图片描述
3.排序+双指针,把三重循环简化成两重循环。

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>>v;
        sort(nums.begin(),nums.end());
        int n=nums.size();
        for(int i=0;i<n;i++){
            if(i>0 && nums[i]==nums[i-1]){
                continue;
            }
            int target = -nums[i];
            int k=n-1;
            for(int j=i+1;j<n;j++){
                if(j>i+1 &&nums[j]==nums[j-1]){
                    continue;
                }
                while(j<k && nums[k]+nums[j]>target){
                    k--;
                }
                if(j==k){
                    break;
                }
                if(nums[k]+nums[j]==target){
                    v.push_back({nums[i],nums[j],nums[k]});
                }
            }    
        }
        return v;
    }
};

在这里插入图片描述
4.只需要找出一组解即可,直接用a+b+c,b+c,c,

#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
long long a,b,c;
for(int i=0;i<n;i++){
cin>>a>>b>>c;
cout<<a+b+c<<" "<<b+c<<" "<<c<<endl;
}
return 0;
}

在这里插入图片描述

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

0x0c……

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值