当前位置:网站首页>LeetCode(剑指 Offer)- 21. 调整数组顺序使奇数位于偶数前面
LeetCode(剑指 Offer)- 21. 调整数组顺序使奇数位于偶数前面
2022-08-08 17:24:00 【放羊的牧码】
题目链接:点击打开链接
题目大意:略
解题思路:略
相关企业
- 字节跳动
AC 代码
- Java
// 解决方案(1)
class Solution {
public int[] exchange(int[] nums) {
int len = nums.length;
List<Integer> l1 = new ArrayList<>();
List<Integer> l2 = new ArrayList<>();
for (int i = 0; i < len; i++) {
if (nums[i] % 2 != 0) {
l1.add(nums[i]);
} else {
l2.add(nums[i]);
}
}
l1.addAll(l2);
int[] rs = new int[len];
for (int i = 0; i < l1.size(); i++) {
rs[i] = l1.get(i);
}
return rs;
}
}
// 解决方案(2)
class Solution {
public int[] exchange(int[] nums) {
int i = 0, j = nums.length - 1, tmp;
while(i < j) {
while(i < j && (nums[i] & 1) == 1) i++;
while(i < j && (nums[j] & 1) == 0) j--;
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
return nums;
}
}
- C++
class Solution {
public:
vector<int> exchange(vector<int>& nums)
{
int i = 0, j = nums.size() - 1;
while (i < j)
{
while(i < j && (nums[i] & 1) == 1) i++;
while(i < j && (nums[j] & 1) == 0) j--;
swap(nums[i], nums[j]);
}
return nums;
}
};
边栏推荐
猜你喜欢
【20210923】Choose the research direction you are interested in?
Fluorescein-PEG-CLS,胆固醇-聚乙二醇-荧光素用于缩短包封周期
DSPE-PEG-Biotin,385437-57-0,磷脂-聚乙二醇-生物素用于生物分子的检测和纯化
以数治企,韧性成长,2022 年中国 CIO 数字峰会成功举行
Open source summer | I have nothing to do during the epidemic, I made a button display box special effect to display my blog
The latest research from PNAS: 81% problem solving rate, neural network Codex opens the door to the world of advanced mathematics
2.5W 字详解线程与锁了,面试随便问!!
【教程2】疯壳·ARM功能手机-测试程序介绍
2 prerequisites for the success of "digital transformation" of enterprises!
Charles MOCK 数据 htpps代理
随机推荐
Cyanine5 tetrazine,Cy5 tetrazineCY5四嗪,1427705-31-4
使用train_test_split划分训练数据集、测试数据集
Tensorflow教程(四)——MNIST项目入门
一、根据系统架构定位系统性能瓶颈
L2-020 功夫传人 (25 分)
Are Huishang Futures official and reliable?Is it safe to open an account in Huishang Futures?
2.5W 字详解线程与锁了,面试随便问!!
Superficial understanding of ports
1.初识MySQL数据库
【CC3200AI 实验教程4】疯壳·AI语音人脸识别(会议记录仪/人脸打卡机)-GPIO
三年软件工程真题
2022-08-08日报:Kaggle所有竞赛开源方案和Top思路汇总
彻底理解 volatile 关键字及应用场景,面试必问,小白都能看懂!
DSPE-PEG-Biotin,385437-57-0,磷脂-聚乙二醇-生物素用于生物分子的检测和纯化
1dp到底多大!
L2-026 小字辈 (25 分)
使用电脑通过VNC Viewer远程连接树莓派4B
六、Jmeter定时器
L2-013 红色警报 (25 分)(并查集)
LeetCode_回溯_中等_491.递增子序列