day16

1.剑指 Offer 45. 把数组排成最小的数

 建议先去看力扣k神的题解,不知道快排原理的可以去百度一下

 i.把字符串化后的两个数字拼在一起有两种拼法,通过比较两种拼法的大小来判断两个数字的“大小”     妙!!!

 ii.通过append函数把字符串连接起来

 1 class Solution {
 2 public:
 3     string minNumber(vector<int>& nums) {
 4       vector<string> str;
 5       int n = nums.size();
 6       for(int i = 0;i < n;i ++)
 7        str.push_back(to_string(nums[i]));
 8       quickSort(str,0,n - 1);
 9       string res;
10       for(auto x : str)
11        res.append(x);
12       return res;
13     }
14 
15     void quickSort(vector<string>& str,int l,int r){
16         if(l >= r) return;
17         int i = l,j = r;
18         while(i < j){
19             while(str[j] + str[l] >= str[l] + str[j] && i < j) j --;
20             while(str[i] + str[l] <= str[l] + str[i] && i < j) i ++;
21             swap(str[i],str[j]);
22         }
23         swap(str[i],str[l]);    //记得把中间值从最左边换到中间
24         quickSort(str,l,i - 1);
25         quickSort(str,i + 1,r);//这两行有分治的感觉
26     }
27 };

 直接使用内置函数sort

 1 class Solution {
 2 public:
 3     string minNumber(vector<int>& nums) {
 4       vector<string> str;
 5       int n = nums.size();
 6       for(int i = 0;i < n;i ++)
 7        str.push_back(to_string(nums[i]));
 8       sort(str.begin(),str.end(),[](string& x,string& y){return x + y < y + x;});
 9       string res;
10       for(auto x : str)
11        res.append(x);
12       return res;
13     }
14 };

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

 逐个验证两个数字(大于0)之间的差

 1 class Solution {
 2 public:
 3     bool isStraight(vector<int>& nums) {
 4       sort(nums.begin(),nums.end());
 5       int i,cnt = 0;
 6       for(i = 0;;i ++)
 7         if(nums[i] == 0) cnt ++;
 8         else break;
 9       i = i + 1; //保证从第二个大于0的整数开始
10       for(;i < 5;i ++){
11          int k = nums[i] - nums[i - 1];
12          if(k == 0) return false;
13          if(k != 1){
14            cnt -= (k - 1);
15            if(cnt < 0) return false;
16          } 
17       }
18       return true;
19     }
20 };

精简版本:从整体来看,如果是顺子的话那么排序后的(大于0)最大值与最小值之间的差必小于等于4,当然,要排除掉有两数相等的情况

 1 class Solution {
 2 public:
 3     bool isStraight(vector<int>& nums) {
 4       sort(nums.begin(),nums.end());
 5       int joker = 0;
 6       for(int i = 0;i < 4;i ++){
 7           if(nums[i] == 0) joker ++;
 8           else if(nums[i] == nums[i + 1]) return false;
 9       }
10       return nums[4] - nums[joker] < 5;
11     }
12 };

 

posted @ 2022-07-12 17:28  balabalahhh  阅读(25)  评论(0)    收藏  举报