当前位置:网站首页>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;
}
边栏推荐
- The selected cells in Excel form have the selection effect of cross shading
- How to Create a Beautiful Plots in R with Summary Statistics Labels
- How to Create a Beautiful Plots in R with Summary Statistics Labels
- Pyqt5+opencv project practice: microcirculator pictures, video recording and manual comparison software (with source code)
- Codeforces 771 div2 B (no one FST, refers to himself)
- YYGH-BUG-05
- Flesh-dect (media 2021) -- a viewpoint of material decomposition
- QT获取某个日期是第几周
- (C语言)八进制转换十进制
- Seriation in R: How to Optimally Order Objects in a Data Matrice
猜你喜欢
Mish shake the new successor of the deep learning relu activation function
The selected cells in Excel form have the selection effect of cross shading
深入理解P-R曲线、ROC与AUC
Natural language processing series (I) -- RNN Foundation
基于Arduino和ESP8266的连接手机热点实验(成功)
Power Spectral Density Estimates Using FFT---MATLAB
GGPLOT: HOW TO DISPLAY THE LAST VALUE OF EACH LINE AS LABEL
GGPlot Examples Best Reference
xss-labs-master靶场环境搭建与1-6关解题思路
Yygh-9-make an appointment to place an order
随机推荐
GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
GGPUBR: HOW TO ADD ADJUSTED P-VALUES TO A MULTI-PANEL GGPLOT
GGPlot Examples Best Reference
Yygh-10-wechat payment
Dynamic memory (advanced 4)
HOW TO CREATE A BEAUTIFUL INTERACTIVE HEATMAP IN R
B high and beautiful code snippet sharing image generation
On data preprocessing in sklearn
How to Easily Create Barplots with Error Bars in R
PyTorch搭建LSTM实现服装分类(FashionMNIST)
(C语言)3个小代码:1+2+3+···+100=?和判断一个年份是闰年还是平年?和计算圆的周长和面积?
How to Easily Create Barplots with Error Bars in R
深入理解PyTorch中的nn.Embedding
GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
浅谈sklearn中的数据预处理
excel表格中选中单元格出现十字带阴影的选中效果
自然语言处理系列(三)——LSTM
The computer screen is black for no reason, and the brightness cannot be adjusted.
SVO2系列之深度濾波DepthFilter
Depth filter of SvO2 series