记一道字节面试题:小于n的最大数
nums = [5,6,8,7] target = 500 nums.sort() target = str(target) def search(nums, target): low, high = 0, len(nums) - 1 while low < high: mid = low + (high - low + 1) // 2 if nums[mid] <= target: low = mid else: high = mid - 1 return nums[low] if nums[low] <= target else -1 def getMaxNumbers(nums, target): res, ans, flag = [], 0, False for i in range(len(target)): if flag: res.append(nums[-1]) continue subtarget = target[i] temp = search(nums, int(subtarget)) if temp == -1: if i == 0: if len(target) == 1: return 0 else: return str(nums[-1]) * (len(target) - 1) else: index = i - 1 while temp == -1 and index >= 0: temp = search(nums, int(target[index]) - 1) index -= 1 if temp == -1: return str(nums[-1]) * (len(target) - 1) res[index + 1] = temp for j in range(index + 2, i): res[j] = nums[-1] res.append(nums[-1]) flag = True else: if temp == int(subtarget): res.append(temp) else: res.append(temp) flag = True for i in range(len(res)): ans = ans * 10 + res[i] return ans print(getMaxNumbers(nums, target))
问题描述:给一个数组nums=[5,4,8,2],给一个n=5416, 让你从nums中选出一些元素,使得组成的数字是小于n的最大数,比如这个例子应该返回5288,当时没想出来,让面试官换了一道题,事后顺着一些大佬的思路写了下,感觉贪心加二分这个思路比较接近正确答案,有没有人看下这个方法行不行