当前位置:网站首页>调整数组顺序使奇数位于偶数前面且相对位置不变
调整数组顺序使奇数位于偶数前面且相对位置不变
2022-07-26 18:25:00 【林纾໌້ᮨ】
1.力扣_调整数组使奇数位于偶数前面
相对位置可能变化的情况:利用双指针left、right,左右同时遍历,左边偶数停止遍历,右边奇数停止遍历,交换left和right对应的值即可。
/**
* 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数在数组的前半部分,所有偶数在数组的后半部分。
**/
public class Num21_奇数位于偶数之前 {
public int[] exchange(int[] nums) {
//双指针i,j,i指向最前面,j指向最后面,i找偶数,j找奇数,找到交换即可
int i=0;
int j=nums.length-1;
while(i<j){
while((i<j)&&(nums[i]&1)!=0){//奇数
i++;
}
while((i<j)&&(nums[j]&1)==0){
j--;
}
if(i<j){
swap(nums,i,j);
}
}
return nums;
}
private void swap(int[] nums, int i, int j) {
int t=nums[i];
nums[i]=nums[j];
nums[j]=t;
}
}
2.调整数组顺序使奇数位于偶数前面且相对位置不变__牛客网
思路:利用插入排序思想,奇数不断前插即可
import java.util.*;
public class Solution {
public void reOrderArray(int [] array) {
int len=array.length;
int k=0;//记录已经排序好的奇数的个数
for(int i=0;i<len;i++){
if((array[i]&1)==1){
int j=i;
//将奇数j交换到k+1位置【奇数不断前插】
while(j>k){
int temp=array[j];
array[j]=array[j-1];
array[j-1]=temp;
j--;
}
//出循环奇数j就交换到了k+1位置,k++继续循环
k++;
}
}
}
}边栏推荐
- C language - Introduction - syntax - string (11)
- 配置服务器环境
- [C language implementation] - dynamic / file / static address book
- MySQL教程:MySQL数据库学习宝典(从入门到精通)
- Pychart loads CONDA to create a pytorch virtual environment and reports an error. It is normal on the CONDA command line
- Difficult performance problems solved in those years -- ext4 defragmentation
- Zbxtable 2.0 heavy release! 6 major optimization functions!
- Don't casually pass the request to the asynchronous thread. You can't handle it. You have to use the startasync method
- Advantages of advanced anti DDoS IP in Hong Kong and which industries are suitable for use
- MySQL tutorial: MySQL database learning classic (from getting started to mastering)
猜你喜欢
随机推荐
EN 1504-7混凝土结构保护和修理用产品钢筋防腐—CE认证
配置服务器环境
如果密钥忘记,多个设备分别不同的密钥,云端是如何同步
测试人员必须知道的软件流程
J1: why is redis so fast + basic structure
[C language implementation] - dynamic / file / static address book
How to write the test case of mobile app? What are the mobile app test points?
Don't casually pass the request to the asynchronous thread. You can't handle it. You have to use the startasync method
EN 1504-6 products for protection and repair of concrete structures - reinforcement anchorage - CE certification
EN 1504-7 products for protection and repair of concrete structures corrosion prevention of reinforcement - CE certification
J3: redis master-slave replication
Tensorflow-GPU 1.15安装
微信小程序插件--wxml-to-canvas(生成图片)
Cannot find current proxy: Set ‘exposeProxy‘ property on Advised to ‘true‘ to make it available
C语言-入门-语法-字符串(十一)
TB 117-2013 US Federal mandatory regulations
[skim] two point answer solution
Cuda11.2 corresponding pytorch installation
EN 1504-6混凝土结构保护和修理用产品钢筋锚固—CE认证
UIAutomator2常用类之UiObject2







