标签:not challenge nothing inline ram app HERE bsp color
Partition an integers array into odd number first and even number second.
Given [1, 2, 3, 4]
, return [1, 3, 2, 4]
Do it in-place.
解题:将一个数组中的奇数和偶数分开,原地分开,不申请额外的空间。思路是,记录好最后一个奇数的后一个位置,也可以理解为偶数中的第一个·。遍历数组,如果当前数组中的元素是偶数,那么什么也不干。如果是奇数,则与记录的那个数交换,直到循环结束。代码如下:
public class Solution {
/*
* @param nums: an array of integers
* @return: nothing
*/
public void partitionArray(int[] nums) {
// write your code here
int odd_index = 0;//最后一个奇数值的后一个
for(int i = 0; i < nums.length; i++){
int temp = nums[i];
if(temp % 2 == 1){
//如果是奇数
nums[i] = nums[odd_index];
nums[odd_index] = temp;
odd_index++;
}else{
//什么也不做
}
}
}
}
373. Partition Array by Odd and Even【LintCode java】
标签:not challenge nothing inline ram app HERE bsp color
原文地址:https://www.cnblogs.com/phdeblog/p/9309171.html