当前位置:网站首页>Leetcode922 按奇偶排序数组 II
Leetcode922 按奇偶排序数组 II
2022-07-02 09:42:00 【魑魅魍魉114】
给定一个非负整数数组 nums, nums 中一半整数是 奇数 ,一半整数是 偶数 。
对数组进行排序,以便当 nums[i] 为奇数时,i 也是 奇数 ;当 nums[i] 为偶数时, i 也是 偶数 。
输入:nums = [4,2,5,7] 输出:[4,5,2,7] 解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
思路:双指针
如果原数组可以修改,则可以使用就地算法求解。
为数组的偶数下标部分和奇数下标部分分别维护指针 i, j。随后,在每一步中,如果 nums[i] 为奇数,则不断地向前移动 j每次移动两个单位,直到遇见下一个偶数。此时,可以直接将 nums[i] 与 nums[j] 交换。我们不断进行这样的过程,最终能够将所有的整数放在正确的位置上。
实现代码:
public int[] sortArrayByParityII(int[] nums) {
int j = 1;
for(int i = 0; i < nums.length; i+=2){
if(nums[i] % 2 == 1){
while(nums[j] % 2 == 1){
j += 2;
}
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
return nums;
}边栏推荐
- PgSQL string is converted to array and associated with other tables, which are displayed in the original order after matching and splicing
- Uniapp uni list item @click, uniapp uni list item jump with parameters
- Industry analysis
- 深入理解PyTorch中的nn.Embedding
- jenkins 凭证管理
- SVO2系列之深度濾波DepthFilter
- to_ Bytes and from_ Bytes simple example
- Cluster Analysis in R Simplified and Enhanced
- 浅谈sklearn中的数据预处理
- Codeforces 771 div2 B (no one FST, refers to himself)
猜你喜欢
![[visual studio 2019] create and import cmake project](/img/51/6c2575030c5103aee6c02bec8d5e77.jpg)
[visual studio 2019] create and import cmake project

How to Create a Beautiful Plots in R with Summary Statistics Labels

Yygh-9-make an appointment to place an order

Three transparent LED displays that were "crowded" in 2022

基于Arduino和ESP8266的Blink代码运行成功(包含错误分析)

自然语言处理系列(二)——使用RNN搭建字符级语言模型

How to Visualize Missing Data in R using a Heatmap

SVO2系列之深度滤波DepthFilter

Deep understanding of NN in pytorch Embedding

Natural language processing series (I) -- RNN Foundation
随机推荐
时间格式化显示
文件操作(详解!)
b格高且好看的代码片段分享图片生成
HOW TO CREATE A BEAUTIFUL INTERACTIVE HEATMAP IN R
Dynamic memory (advanced 4)
YYGH-BUG-04
php 根据经纬度查询距离
动态内存(进阶四)
How to Add P-Values onto Horizontal GGPLOTS
YYGH-9-预约下单
[visual studio 2019] create MFC desktop program (install MFC development components | create MFC application | edit MFC application window | add click event for button | Modify button text | open appl
HOW TO ADD P-VALUES ONTO A GROUPED GGPLOT USING THE GGPUBR R PACKAGE
conda常用命令汇总
Flesh-dect (media 2021) -- a viewpoint of material decomposition
GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
How does Premiere (PR) import the preset mogrt template?
Visualization of chip SEQ data by deeptools
How to Visualize Missing Data in R using a Heatmap
CONDA common command summary
【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)