当前位置:网站首页>Leetcode922 sort array by parity II
Leetcode922 sort array by parity II
2022-07-02 12:05:00 【Monsters 114】
Given an array of nonnegative integers nums, nums The middle half integer is Odd number , Half the whole number is even numbers .
Sort the array , For convenience nums[i] In an odd number of ,i It's also Odd number ; When nums[i] For even when , i It's also even numbers .
Input :nums = [4,2,5,7] Output :[4,5,2,7] explain :[4,7,2,5],[2,5,4,7],[2,7,4,5] It will also be accepted .
Ideas : Double pointer
If the original array can be modified , Then the local algorithm can be used to solve .
Maintain pointers for the even and odd subscript parts of the array respectively i, j. And then , At each step , If nums[i] It's odd , And keep moving forward j Move two units at a time , Until I meet the next even number . here , You can directly nums[i] And nums[j] In exchange for . We continue this process , Finally, all integers can be put in the correct position .
Implementation code :
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;
}
边栏推荐
猜你喜欢
K-Means Clustering Visualization in R: Step By Step Guide
PyTorch搭建LSTM实现服装分类(FashionMNIST)
Power Spectral Density Estimates Using FFT---MATLAB
SVO2系列之深度滤波DepthFilter
GGPLOT: HOW TO DISPLAY THE LAST VALUE OF EACH LINE AS LABEL
【2022 ACTF-wp】
R HISTOGRAM EXAMPLE QUICK REFERENCE
YYGH-BUG-05
GGPUBR: HOW TO ADD ADJUSTED P-VALUES TO A MULTI-PANEL GGPLOT
Jenkins用户权限管理
随机推荐
qt 仪表自定义控件
求16以内正整数的阶乘,也就是n的阶层(0=<n<=16)。输入1111退出。
Applet link generation
Yygh-10-wechat payment
基于Arduino和ESP8266的Blink代码运行成功(包含错误分析)
Codeforces 771-div2 C (trouble, permutation is not very good)
PgSQL string is converted to array and associated with other tables, which are displayed in the original order after matching and splicing
PHP query distance according to longitude and latitude
进入前六!博云在中国云管理软件市场销量排行持续上升
ORB-SLAM2不同线程间的数据共享与传递
HR wonderful dividing line
Lekao: contents of the provisions on the responsibility of units for fire safety in the fire protection law
Those logs in MySQL
Industry analysis
[QT] Qt development environment installation (QT version 5.14.2 | QT download | QT installation)
Log4j2
HOW TO ADD P-VALUES TO GGPLOT FACETS
Power Spectral Density Estimates Using FFT---MATLAB
Deep understanding of NN in pytorch Embedding
XSS labs master shooting range environment construction and 1-6 problem solving ideas