本文主要是介绍LintCode on Array by Odd and Even,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
description:
Partition an integers array into odd number first and even number second.
Have you met this question in a real interview? Yes
Example
Given [1, 2, 3, 4], return [1, 3, 2, 4]
非常简单,直接使用two pointers 的算法就能够非常好的处理。
public class Solution {/*** @param nums: an array of integers* @return: nothing*/public void partitionArray(int[] nums) {// write your code here;if (nums == null || nums.length == 0 || nums.length == 1) {return;}int left = 0;int right = nums.length - 1;while (left <= right) {if (left >= right) {return;}while (left <= right && nums[left] % 2 == 1) {left++;}while (left <= right && nums[right] % 2 == 0) {right--;}if (left <= right) {int temp = nums[left];nums[left] = nums[right];nums[right] = temp;left++;right--;}}}
}
这篇关于LintCode on Array by Odd and Even的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!