当前位置:网站首页>Sword finger offer 21. adjust the array order so that odd numbers precede even numbers
Sword finger offer 21. adjust the array order so that odd numbers precede even numbers
2022-07-24 18:19:00 【[email protected]】

https://leetcode.cn/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
Their thinking : Double finger needling
Left pointer left Traverse from left to right , Stop when an even number is encountered ; Right pointer left Traverse from right to left , Stop when an odd number is encountered ; Exchange the odd and even numbers encountered at the same time
class Solution {
public int[] exchange(int[] nums) {
int left=0,right=nums.length-1;
while(left<right){
while(left<right&&nums[left]%2==1){
left++;
}
while(left<right&&nums[right]%2==0){
right--;
}
swap(nums,left,right);
}
return nums;
}
public void swap(int[] nums,int i,int j){
int tmp=nums[i];
nums[i]=nums[j];
nums[j]=tmp;
}
}
//O(n)
//O(1)
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int l=0,r=nums.size()-1;
while(l<r){
while(l<r&&nums[l]%2==1){
l++;
}
while(l<r&&nums[r]%2==0){
r--;
}
swap(nums[l],nums[r]);
}
return nums;
}
};
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
left,right=0,len(nums)-1
while left < right:
while left<right and nums[left]%2==1:
left+=1
while left<right and nums[right]%2==0:
right-=1
nums[left],nums[right]=nums[right],nums[left]
return nums
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/205/202207241815443051.html
边栏推荐
- [OBS] dependency Library: x264 vs Build
- redis集群的三种方式
- 05mysql lock analysis
- About the writing method of interface 1 chain interpretation 2. Method execution (finally) must be executed
- 运维小白成长记——架构第8周
- The drop-down list component uses iscrol JS to achieve the rolling effect of the pit encountered
- In depth analysis of the famous Alibaba cloud log4j vulnerability
- 0612~quartz定时器框架
- jmeter --静默运行
- Blackmagic Fusion Studio 18
猜你喜欢
随机推荐
Baidu touch.js
Pycharm configuring opencv Library
空间三点画圆代码
Growth of operation and maintenance Xiaobai - week 8 of Architecture
Still building projects from scratch? This upgraded rapid development scaffold is worth a try!
Variable and immutable data types
[opencv] - thresholding
Go to bed capacity exchange
移动端实现0.5px的实用方案
ORM student management system
Template syntax [easy to understand]
File upload vulnerability -.User.ini and.Htaccess
Polymorphism, abstract class, interface
steam API
Shanghai Jiaotong University team used joint deep learning to optimize metabonomics research
猜JWT关键字
Section 11 cache avalanche, hot data failure follow Daewoo redis ------- directory post
Inherit, override, overload
SSM framework learning
Inheritance and Derive




![[OBS] dependency Library: x264 vs Build](/img/24/4caea5dc6ff092a3161f43b6026d25.png)


