从未排序的整数数组中生成一个交替定位的奇数和偶数的列表...

时间:2013-11-18 06:30:57

标签: arrays

我有一个半小时的采访微软的实习职位,我被要求生成一个列表,从一个未排序的整数数组中,或者定位奇数和偶数, 我对这个问题的解决方案如下,我想这是因为我没有得到报价,因此低于面试官的期望,任何人都可以给我一些提示来改进我的代码吗?

import java.util.ArrayList;


public class EvenOddArray {

private int min(int n, int m)
{
    int min;
    if (n > m){
        min = m;
    }
    else {
        min = n;
    }
    return min;
}


public ArrayList<Integer> generateEvenOddArray(int[] list)
{
    ArrayList<Integer> oddList = new ArrayList<Integer>();
    ArrayList<Integer> evenList = new ArrayList<Integer>();
    ArrayList<Integer> resultList = new ArrayList<Integer>();

    for (int number : list) {
        if (number%2 == 0){
            evenList.add(number);
        }
        else {
            oddList.add(number);
        }

    }


    int numberOfEvenNumbers = evenList.size();
    int numberOfOddNumbers = oddList.size();
    int minOfOddAndEven = min(numberOfEvenNumbers,numberOfOddNumbers);
    ArrayList<Integer> longestList = getLongestList(evenList,oddList);

    int i ;
    for (i = 0; i < minOfOddAndEven; i++) {
        resultList.add(2*i,oddList.get(i) );
        resultList.add(2*i+1,evenList.get(i));          
    }
    if(longestList != null ){
        for (int j = i; j < longestList.size(); j++) {
            resultList.add(longestList.get(j));
        }
    }
    return resultList;


}
private ArrayList<Integer> getLongestList(ArrayList<Integer> listone,
        ArrayList<Integer> listTwo) {
    if (listone.size()<listTwo.size()){
        return listTwo;
    }
    else if (listone.size()>listTwo.size()){
        return listone;
    }
    return null;
}

0 个答案:

没有答案