Sword refers to Offer 61-Straight in playing cards C++

Title description

Insert picture description here

Solution ranking

class Solution {
    
    
public:
    bool isStraight(vector<int>& nums) {
    
    
        int super = 0;
        sort(nums.begin(), nums.end());
        for(int i = 0; i < nums.size() - 1; i++){
    
    
            if(nums[i] == 0) {
    
    
                super ++;
                continue;
            }
            if(nums[i] == nums[i+1]) return false;
            super -= nums[i + 1] - nums[i] - 1;
            if(super < 0) return false;
        }
        return true;
    }
};

Insert picture description here
Time complexity O(NlogN)
Space complexity O(1)

Solution set

The big guy’s approach guarantees two conditions

  1. All elements except 0 are not repeated
  2. Element maximum value-element minimum value is less than 5
    C++ set insert is used, and c++ cannot directly return the maximum and minimum value of the set
class Solution {
    
    
public:
    bool isStraight(vector<int>& nums) {
    
    
        set<int> s;
        int max = -1;
        int min = 15;
        for(int num : nums) {
    
    
            if(s.find(num) != s.end() && num != 0) return false;
            else {
    
    
                s.insert(num);
                if(num > max) max = num;
                if(num < min && num != 0) min = num;   
            } 
        }
        return max - min < 5 ? true : false;
    }
};

To be concise, you can write it like this

class Solution {
    
    
public:
    bool isStraight(vector<int>& nums) {
    
    
        set<int> s;
        int max = -1;
        int min = 15;
        for(int num : nums) {
    
    
            if(num == 0) continue;
            if(s.find(num) != s.end() && num != 0) return false;
            s.insert(num);
            if(num > max) max = num;
            if(num < min) min = num;   
        } 
        return max - min < 5 ? true : false;
    }
};

Time complexity O(NlogN)
Space complexity O(N)
The add complexity of java's hashset is O(1), so the overall is O(N)

Guess you like

Origin blog.csdn.net/qq_42883222/article/details/112725644