Skip to content

Commit

Permalink
刷算法,调整数组顺序
Browse files Browse the repository at this point in the history
  • Loading branch information
yangchong211 committed Mar 31, 2022
1 parent 993c3ba commit 6b58bf4
Showing 1 changed file with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,36 @@ int maxProfit(int[] prices) {
return count;
}

/**
* 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
*/
public class Solution {
public void reOrderArray(int [] array) {
//如果数组长度等于0或者等于1,什么都不做直接返回
if(array.length==0||array.length==1)
return;
//oddCount:保存奇数个数
//oddBegin:奇数从数组头部开始添加
int oddCount=0,oddBegin=0;
//新建一个数组
int[] newArray = new int[array.length];
//计算出(数组中的奇数个数)开始添加元素
for(int i=0;i<array.length;i++){
if((array[i]&1)==1) oddCount++;
}
for(int i=0;i<array.length;i++){
//如果数为基数新数组从头开始添加元素
//如果为偶数就从oddCount(数组中的奇数个数)开始添加元素
if((array[i]&1)==1)
newArray[oddBegin++]=array[i];
else newArray[oddCount++]=array[i];
}
for(int i=0;i<array.length;i++){
array[i]=newArray[i];
}
}
}

private class MyThread implements Runnable{
@Override
public void run() {
Expand Down

0 comments on commit 6b58bf4

Please sign in to comment.