• 剑指offer面试题14-调整数组顺序使奇数位于偶数前面


    题目:

    输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得全部奇数位于数组的前半部分。全部偶数位于数组的后半部分。


    前后分的这个。,让我想起来高速排序。好吧,就用这个做。

    考虑到了排序的可扩展性,这里的推断条件设置为接口。


    package com.aii.algorithm;
    
    public class ArrayAdjuster {
    
    	public void adjust(int[] array, CallBack callBack) {
    		if (array == null) {
    			throw new RuntimeException();
    		}
    
    		partition(array, 0, array.length - 1, callBack);
    	}
    
    	// 在快排的基础上增加了一个接口
    	private void partition(int[] array, int start, int end, CallBack condition) {
    		if (array.length == 0) {
    			return;
    		}
    
    		int tmp = array[start];
    		int tmpIndex = start++;
    		while (start < end) {
    			while (start < end && !condition.event(array[end])) {
    				end--;
    			}
    			if (start < end && condition.event(array[end])) {
    				array[tmpIndex] = array[end];
    				tmpIndex = end--;
    			}
    
    			//
    			while (start < end && condition.event(array[start])) {
    				start++;
    			}
    			if (start < end && !condition.event(array[start])) {
    				array[tmpIndex] = array[start];
    				tmpIndex = start++;
    			}
    		}
    		array[tmpIndex] = tmp;
    	}
    
    	public interface CallBack {
    		boolean event(int i);
    	}
    }
    


    測试用例

    package com.aii.algorithm;
    
    import java.util.Arrays;
    
    import org.junit.Test;
    
    import com.aii.algorithm.ArrayAdjuster.CallBack;
    
    public class ArrayAdjusterTest {
    
    	@Test
    	public void test() {
    		int[] a = { 1, 2, 3, 4, 6, -2, -3, 0, 1, -1 };
    		new ArrayAdjuster().adjust(a, new CallBack() {
    
    			@Override
    			public boolean event(int i) {
    				if (i % 2 == 0) {
    					return false;
    				}
    				return true;
    			}
    		});
    		System.out.println(Arrays.toString(a));
    	}
    
    }
    

    结果:
    [-1, 1, 3, -3, 1, -2, 6, 0, 4, 2]




  • 相关阅读:
    python 上传下载文件
    post方式加载iframe
    js 实现打印功能
    python 判断数据类型
    web样式无法正常显示
    C# 调用python
    PDF转换成Txt
    js预览PDF的插件(亲测支持IE9,火狐,等等)
    文件下载
    asp.net网站发布到服务器GET的技能
  • 原文地址:https://www.cnblogs.com/zsychanpin/p/7102553.html
Copyright © 2020-2023  润新知