[LeetCode 1,7] [Simple] + and two integer numbers of reverse

Personal obsessive-compulsive disorder, not from the water problems started feeling uncomfortable, not used LeetCode, to just rice, problems started.

1. The sum of two numbers

Topic Link

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int>tmp=nums;
        sort(nums.begin(),nums.end());
        int st = 0, ed = nums.size()-1;
        while(st<ed){
            if(nums[st]+nums[ed]==target)break;
            if(nums[st] + nums[ed] < target)st++;
            if(nums[st] + nums[ed] > target)ed--;
        }
        int ans1=0,ans2=nums.size()-1;
        while(tmp[ans1]!=nums[st])ans1++;
        while(tmp[ans2]!=nums[ed])ans2--;
        if(ans1>ans2)swap(ans1,ans2);
        return vector<int>{ans1,ans2};
    }
};

First wrote a violent sort + dual pointers, 4ms
did not give a date range to see time not too would like to write a unordered_map, the idea is to throw ca map where to find b

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int>mmp;
        int a1;
        for(a1=0;a1<nums.size();a1++){
            if(mmp.count(nums[a1]))return {mmp[nums[a1]],a1};
            mmp[target-nums[a1]]=a1;
        }
        return {};
    }
};

Or write a bit, 8ms, feel or see evaluation Kyi state.

7. integer reversal

Topic Link

typedef long long LL;
class Solution {
public:
    int reverse(int x) {
        LL p=0,f=x<0?-1:1,xx=abs((LL)x);
        while(xx){
            p*=10;
            p+=xx%10;
            xx/=10;
        }
        p*=f;
        if(p<INT_MIN||p>INT_MAX)p=0;
        return p;
    }
};
Published 73 original articles · won praise 13 · views 20000 +

Guess you like

Origin blog.csdn.net/IDrandom/article/details/103465599