当前位置:网站首页>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;
}
};边栏推荐
猜你喜欢
随机推荐
Is it safe to open an account with CICC Wealth?How does it work?
手机ETF基金开户哪家证券公司好?哪个更安全
Detailed explanation of JVM memory model and structure (five model diagrams)
【TypeScript】函数类型:返回值类型和参数类型到底如何定义?
三年软件工程真题
L2-016 愿天下有情人都是失散多年的兄妹 (25 分)
[In-depth study of 4G/5G/6G topic-54]: L3 signaling control-3-segmentation of software functions and processes-signaling of CU-UP network elements
L2-024 部落 (25 分)(并查集)
Tensorflow教程(二)——基本概念与搭建流程
Getting started with glide4
LeetCode_二叉树_中等_515.在每个树行中找最大值
第二十章 源代码文件 REST API 参考(二)
C人脸识别
2.MySQL链接和创建数据库,创建数据表
使用train_test_split划分训练数据集、测试数据集
Qt——选择文件夹并获取路径以及文件夹下子文件
LeetCode_回溯_中等_491.递增子序列
PNAS最新研究:81%解题率,神经网络 Codex 推开高等数学世界大门
The new version of squirrel as source change operation
并发与并行









