奇数置于数组前半部分偶数置于数组后半部分

奇数置于数组前半部分偶数置于数组后半部分

/*	剑指offer21,输入一个整数数组,实现一个函数来调整该数组中数字的顺序,
 * 				使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
 * 	解题思路:
 * 			1.遍历数组当遇到偶数时,将该偶数后的所有数字前移一位,偶数放到数组的最后。
 * 			这种方法的时间复杂度为o(n**2)
 * 			2.双指针法,头指针指向数组头、尾指针指向数组尾
 * 			    移动头指针,如果头指针指向奇数头指针后移
 * 			    如果头指针指向偶数,尾指针指向奇数,交换两指针的值
 * 			    尾指针指向偶数,前移尾指针直到尾指针指向奇数
 * 
 * 	测试:
 * 		null
 * 		{}
 * 		{1,2,3,4,5,6}
 * 		{2,2,2,1,1,1}
 * 		{1,1,1,2,2,2}
 * 		{1,1,1,1,1,1}
 * 		{1}
 * */
public class Offer21 {
	public static void main(String[] args) {
		Offer21Solution2 solution2 = new Offer21Solution2();
		int[] nums = {1};
		solution2.exchange(nums);
		for (int i : nums) {
			System.out.print(i);
		}
	}
}

class Offer21Solution1 {
    public int[] exchange(int[] nums) {
    	if(nums==null || nums.length==1) return nums;
    	int i = 0;
    	int num = 0;
    	while(num < nums.length) {
    		//如果nums[i]是偶数,nums[i]之后的数字前移一位,nums[i]赋值到最后
    		if(nums[i]%2==0) {
    			int temp = nums[i];
    			for(int j=i;j<nums.length-1;j++) {
    				nums[j] = nums[j+1];
    			}
    			nums[nums.length-1]=temp;
    			if(nums[i]%2==0) i--;
    		}
    		i++;
    		num++;
    	}
    	return nums;
    }
}

class Offer21Solution2{
	public int[] exchange(int[] nums) {
		if(nums==null || nums.length==1 || nums.length==0) return nums;
		int head = 0;
		int tail = nums.length-1;
		while(head!=tail) {
		//	System.out.println(head+" "+tail);
			if(nums[head]%2==0) {
				if(nums[tail]%2!=0) {
					int temp = nums[head];
					nums[head] = nums[tail];
					nums[tail] = temp;
				}else if(nums[tail]%2==0) {
					while(nums[tail]%2==0) {
						if(head==tail) return nums;
						tail--;
					}
					int temp = nums[head];
					nums[head] = nums[tail];
					nums[tail] = temp;
				}
			}
			head++;
		}
		return nums;
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值