title: Daily Practice (33): Straight in Poker
categories:[Swords offer]
tags:[Daily practice]
date: 2022/03/08
Daily Practice (33): Straight in Poker
Randomly draw 5 cards from several decks of cards, and judge whether it is a straight, that is, whether the 5 cards are consecutive. 2 to 10 are the numbers themselves, A is 1, J is 11, Q is 12, K is 13, and the big and small kings are 0, which can be regarded as any number. A cannot be considered as 14.
Example 1:
Input: [1,2,3,4,5]
output: True
Example 2:
Input: [0,0,1,2,5]
output: True
limit:
Array length is 5
The value of the array is [0, 13] .
Source: LeetCode
Link: https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof
Method 1: No sorting method
Algorithm flow:
1. The maximum value maxValue and the minimum value minValue among the 5 playing cards, then we know that it takes maxValue - minValue + 1 card to make it a straight.
In the process of finding maxValue and minValue, skip size 0.
If maxValue - minValue + 1 > 5, it means that the 5 cards given by the question are not enough to form a straight, and return false .
- Even if there are big and small kings in it, it is not enough to fill it up to make it a straight.
Returns true if maxValue - minValue + 1 <= 5, indicating that 5 cards are enough to form a straight.
- The big and small kings inside can be filled in the appropriate position.
2. At the same time, we define a flag array to judge whether there are repeated numbers, and if the repeated numbers are found, return false directly.
bool isStraight(vector<int>& nums) {
bool m[15];
memset(m, 0, sizeof(m));
int minValue = 14, maxValue = 0;
for (int item : nums) {
if (item == 0) {
continue;
}
if (m[item]) {
return false;
}
m[item] = true;
minValue = min(minValue, item);
maxValue = max(maxValue, item);
}
return (maxValue - minValue + 1 <= 5);
}
Method 2: Sort by
Algorithm flow:
After sorting, the poker cards are in order, and we can directly judge how many kings or kings are needed to fill the space between two adjacent cards.
- If the number of big and small kings to be filled is greater than the number of existing big and small kings, return false
- Conversely, return true if the number of big and small kings to be filled is less than or equal to the number of existing big and small kings
bool isStraight(vector<int>& nums) {
sort(nums.begin(), nums.end()); //排序
int zero = 0;
for (int i = 0; i < 4; i++) {
if (nums[i] == 0) { //计数大小王
zero++;
continue;
}
if (nums[i] == nums[i+1]) {//有重复
return false;
}
zero -= nums[i+1] - nums[i] - 1;//需要填补大小王的数量
}
return zero >= 0;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。