当前位置:网站首页>Adjust the array order so that odd numbers precede even numbers - two questions per day
Adjust the array order so that odd numbers precede even numbers - two questions per day
2022-07-28 07:35:00 【Ink man bookworm】
The finger of the sword Offer 21. Adjust the array order so that the odd Numbers precede the even Numbers
It's time to get up and brush questions every morning , It's really interesting to brush questions , Two questions a day , Come on ️

Enter an array of integers , Implement a function to adjust the order of the Numbers in the array , Make all odd numbers in the first half of the array , All even numbers are in the second half of the array .
Example :
Input :nums = [1,2,3,4]
Output :[1,3,2,4]
notes :[3,1,2,4] And one of the right answers .
Tips :
0 <= nums.length <= 500000 <= nums[i] <= 10000
Ideas
Algorithm : Double pointer .
First, because ordered arrays , So the basic judgment is double pointer , Judge whether the number is odd
nums[left]%2==1, If the left pointer is an odd number, move it right , If the right pointer is even, move left , If two pointers , On the left is an even number , On the right is the odd number , Exchange with each other , This problem is over .
public class Adjust the array order so that the odd Numbers precede the even Numbers {
public int[] exchange(int[] nums) {
int left=0;
int right=nums.length-1;
int temp=0;
while (left<right){
if (nums[left]%2==1){
left++;
}else if (nums[right]%2==0){
right--;
}else {
temp=nums[left];
nums[left]=nums[right];
nums[right]=temp;
left++;
right--;
}
}
return nums;
}
}
边栏推荐
猜你喜欢

Soft exam certificate can be used like this! Get a certificate = get a professional title?

如何理解CMS回收器降低gc停顿时间

Learning to estimate 3D hand pose from single RGB image & amp notes

ThreadLocal things

DNA修饰金属铑Rh纳米颗粒RhNPS-DNA(DNA修饰贵金属纳米颗粒)

How low-end computers learn secrets in depth - using the mistgpu computing platform

Isolation level RR, gap lock, unreal reading

EMC整改思路

User mode vs kernel mode, process vs thread

Eventbus of guava
随机推荐
JS upload file method
牛客Mysql——SQL必知必会
铜铟硫CuInSe2量子点修饰DNA(脱氧核糖核酸)DNA-CuInSe2QDs(齐岳)
Eventbus of guava
Big talk persistence and redolog
RFID辐射测试小结
List of papers on gestures
分布式系分发展概览
guava之guava cache
通过sed 修改conf文件
EMC rectification ideas
收藏 | 结合个人经验,我总结了这7点EMC相关知识
Modify the conf file through sed
近红外二区AgzS量子点包裹脱氧核糖核酸DNA|DNA-AgzSQDs(齐岳)
移动端H5输入框调起手机软键盘,导致底部固定定位被顶起解决方法
【干货】32个EMC标准电路分享!
Summary of project experience
Map uses tuple to realize multiple value values
“核弹级” Log4j 漏洞仍普遍存在,并造成持续影响
[a little knowledge] AQS