当前位置:网站首页>LeetCode刷题笔记:1403.非递增顺序的最小子序列
LeetCode刷题笔记:1403.非递增顺序的最小子序列
2022-08-07 06:40:00 【LeBron Le】
1. 问题描述
给你一个数组 nums,请你从中抽取一个子序列,满足该子序列的元素之和 严格 大于未包含在该子序列中的各元素之和。
如果存在多个解决方案,只需返回 长度最小 的子序列。如果仍然有多个解决方案,则返回 元素之和最大 的子序列。
与子数组不同的地方在于,「数组的子序列」不强调元素在原数组中的连续性,也就是说,它可以通过从数组中分离一些(也可能不分离)元素得到。
注意,题目数据保证满足所有约束条件的解决方案是 唯一 的。同时,返回的答案应当按 非递增顺序 排列。
2. 解题思路
① 首先对 nums 数组排序(升序)
② 使用一个 ArrayList 存储结果序列 res
③ 遍历 nums 数组计算整个数组总和
④ 取数组总和的一半作为比较对象
⑤ 从排序后的升序数组最后一个元素开始遍历,逐个加入 res,并计算当前子序列总和与原数组总和的一半进行比较,如果大于则终止遍历。
⑥ 返回存储结果序列 res
3. 代码实现
class Solution {
public List<Integer> minSubsequence(int[] nums) {
Arrays.sort(nums);
List<Integer> res = new ArrayList<>();
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}
sum /= 2;
int sonsum = 0;
for (int i = nums.length - 1; i >= 0; i--) {
sonsum += nums[i];
res.add(nums[i]);
if (sonsum > sum) {
break;
}
}
return res;
}
}
4. 执行结果
执行结果:通过
执行用时:3 ms, 在所有 Java 提交中击败了95.47%的用户
内存消耗:41.6 MB, 在所有 Java 提交中击败了66.29%的用户
通过测试用例:103 / 103
边栏推荐
猜你喜欢

LeetCode's sword is Offer 06. Print the linked list from end to end

数组扁平化

2022A Special equipment related management (elevator) special work permit test question bank simulation test platform operation

How to use the @Async annotation

servlet tutorial 2: return to the jsp page

LeetCode 剑指 Offer 24. 反转链表

@Async注解的使用方法

赋值、深拷贝、浅拷贝、堆和栈

netstat&firewall

明明加了唯一索引,为什么还是产生重复数据?
随机推荐
spyder/conda安装包报错:conda info could not be constructed. KeyError: ‘pkgs_dirs‘
MySQL - 索引优化
毕设-基于SSM在线电影订票系统
TRACE32——变量显示选项Setup.Var
lottie-web,lottie动画使用详解
“蔚来杯“2022牛客暑期多校训练营3
LeetCode sword refers to Offer 09. Two stack is used to implement a queue
How to use the @Async annotation
LeetCode's sword is Offer 06. Print the linked list from end to end
2022A Special equipment related management (elevator) special work permit test question bank simulation test platform operation
Are there MCUs with 5nm process technology?
Graph Theory and Network Models - Based on R
【问题记录】一次由filter引发的血案,如何定位上游链路的问题,问题排查与定位思路分享
WEB安全基础 - - -弱口令和暴力破解
MySQL - index optimization
【n-piece chess】
数组扁平化
servlet 教程 2:返回 jsp 页面
基于ESP32的蓝牙鼠标键盘(一)BleKeyboard.h函数解析
LeetCode 剑指 Offer 06. 从尾到头打印链表