当前位置:网站首页>剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
2022-07-24 18:15:00 【[email protected]】

https://leetcode.cn/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
解题思路:双指针法
左指针left从左往右遍历,当遇到一个偶数时停止;右指针left从右往左遍历,当遇到一个奇数时停止;同时交换遇到的奇数和偶数
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://blog.csdn.net/qq_43478694/article/details/125955655
边栏推荐
- The drop-down list component uses iscrol JS to achieve the rolling effect of the pit encountered
- 0613 ~ self study
- pinia 入门及使用
- T245982 「KDOI-01」醉花阴
- Common methods of number and math classes
- pycharm配置opencv库
- 0625~<config>-<bus>
- Several sorting methods for while and sort
- Just one dependency to give swagger a new skin, which is simple and cool!
- 如何用WebGPU流畅渲染百万级2D物体?
猜你喜欢
随机推荐
Shanghai Jiaotong University team used joint deep learning to optimize metabonomics research
Model saving and loading of sklearn
如何遵循“低耦合”设计原则?
ES6 cycle filter value
【OpenCV】—阈值化
IO multiplexing
0625~<config>-<bus>
sklearn 的模型保存与加载使用
Common methods of string (2)
猜JWT关键字
pycharm配置opencv库
0625~<config>-<bus>
Go language interface and type
0701~ holiday summary
颜色的13 个必备方法!
【校验】只能输入数字(正负数)
Baidu touch.js
如何用WebGPU流畅渲染百万级2D物体?
Interview assault 66: what is the difference between request forwarding and request redirection?
PXE efficient batch network installation








