力扣leetcode1363. 形成三的最大倍数
题目设置了每个元素都是单个数字,因此可以用拆开成10位的讨巧做法,但如果不限制大小,那么只能按余数处理,其他高赞解也写得很清楚了,详细算法可以看下其他解,大致思路如下:
首先确定一点,在满足条件的情况下,答案长度越长,数字越大,即1000大于999,在长度相同的情况下,比较大小,因此先尽量地增加答案长度
将输入的数字分为三类,余0、余1和余2,余0的全部都放进答案,因为一定整除
将余1的和余2的排序后放入前面3n个(比如余2的数字总共7个,就放进去最大的6个,剩1个,若总共6个,放进去3个,剩3个,除非总共0个,否则最终剩1、2或者3个,至于为什么要剩3个,举例2 2 1 1 1)
然后剩下的余1和余2的(0-6个数)有多种组合方式,就是中间if那一段,把所有的情况都加入备选方案,然后按长度排序,如果长度相同,按大小排序(均是降序),然后取第一个加入答案
最终将答案所有数字降序排序然后连起来即可
可能程序还有问题,望指正
因为涉及排序和转换,速度不算快
1 class Solution(object): 2 def largestMultipleOfThree(self, digits): 3 remain0, remain1, remain2 = [], [], [] 4 5 for i in digits: 6 temp = i % 3 7 if 0 == temp: 8 remain0.append(i) 9 elif 1 == temp: 10 remain1.append(i) 11 else: 12 remain2.append(i) 13 14 remain1, remain2 = sorted(remain1, reverse=True), sorted(remain2, reverse=True) 15 len1, len2 = len(remain1), len(remain2) 16 max1, max2 = 3 * int(len1 / 3), 3 * int(len2 / 3) 17 if max1 == len1: 18 max1 -= 3 19 if max2 == len2: 20 max2 -= 3 21 remain0 += remain1[:max1] + remain2[:max2] 22 remain1, remain2 = remain1[max1:], remain2[max2:] 23 # print(max1, max2) 24 25 len1, len2 = len(remain1), len(remain2) 26 pending = [] 27 if (len1 == 0 or len1 == 3) and (len2 == 0 or len2 == 3): 28 pending.append(remain1 + remain2) 29 if len1 == 3: 30 pending.append(remain1) 31 if len2 == 3: 32 pending.append(remain2) 33 if len(remain1) >= 2 and len(remain2) >= 2: 34 pending.append(remain1[:2] + remain2[:2]) 35 if len(remain1) >= 1 and len(remain2) >= 1: 36 pending.append(remain1[:1] + remain2[:1]) 37 pending = sorted(pending, key=lambda x: self.comp(x)) 38 # print(pending) 39 if pending: 40 remain0 += pending[0] 41 42 if not remain0: 43 return "" 44 remain0 = sorted(remain0, reverse=True) 45 ans, flag = "", 1 46 for i in remain0: 47 if flag: 48 if i: 49 flag = 0 50 else: 51 continue 52 ans += str(i) 53 if not ans: 54 return "0" 55 else: 56 # print(ans) 57 return ans 58 59 def comp(self, x): 60 sum_len, sum_num = 0, "" 61 for i in x: 62 str_i = str(i) 63 sum_len += len(str_i) 64 sum_num += str_i 65 if sum_num: 66 return [-sum_len, -int("".join(sorted(sum_num, reverse=True)))] 67 else: 68 return [-sum_len, 0]