剑指offer_2020_9_21

剑指 Offer 61. 扑克牌中的顺子

class Solution {
public:
    bool isStraight(vector<int>& nums) {
    sort(nums.begin(),nums.end());
    int id=0;
    while(nums[id]==0) id++;//id为0个数
    int count=0;
    for(int i=id+1;i<nums.size();i++)
    {
        if(nums[i]==nums[i-1]) return false;
        count+=nums[i]-nums[i-1]-1;//需要0的个数
    }
    return count<=id;
    }
};

剑指 Offer 62. 圆圈中最后剩下的数字

class Solution {
public:
    int lastRemaining(int n, int m) {
        int ret = 0;
        for (int i = 2; i <= n; i++) {
            ret = (ret + m) % i;
        }
        return ret;
    }
};

剑指 Offer 63. 股票的最大利润

class Solution {
public:
    int maxProfit(vector<int>& prices) {
    if(prices.empty()||prices.size()<2) return 0;
    int res=0,minn=prices[0];
    for(int i=1;i<prices.size();i++)
    {
        if(prices[i]<=minn)
        minn=prices[i];
        else
        {
            res=max(res,prices[i]-minn);
        }
    }
    return res;
    }
};

剑指 Offer 64. 求1+2+…+n

class Solution {
public:
    int sumNums(int n) {
    return (int)(pow(n,2)+n)>>1;
    }
};

剑指 Offer 65. 不用加减乘除做加法(^无进位求和,&求进位)

class Solution {
public:
    int add(int a, int b) {
    while(b!=0)
    {
        int tmp=a^b;
        b=((unsigned int)(a&b)<<1);
        a=tmp;
    }
    return a;
    }
};
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页