Get Next With Duplicate of Even Index

题目:
第一道设计一个iterator, 输入一个数组[3,8,1,9,2,12] 每次调用next()得到8,8,8,9,12,12 问了半天才明白就是

解题思路:
这道题就是用自己做的数据结构来做,时间和空间都是O(n)

代码:

public class GetNextWithDuplicateofEvenIndex {
    /*       input: 3,8,1,9,2,12       output: 8,8,8,9,12,12    */
    public List<Pair> list;

    public GetNextWithDuplicateofEvenIndex(int[] nums){
        // assuming that the length of nums is even        list = new LinkedList();
        int count = 0;
        int i = 1;
        // assuming that length of nums is not 0        for( ; i <= nums.length - 1; i += 2){
            if(nums[count] > 0) {
                Pair pair = new Pair(nums[i], nums[count]);
                list.add(pair);
            }
            count += 2;
        }
    }

    // return -1 if the "list" is empty    public int next(){
        if(list.isEmpty()){
            return -1;
        }
        else{
            Pair pair = list.get(0);
            list.remove(0);
            int count = pair.getY();
            int val = pair.getX();
            if(count != 1){
                pair.setY(count - 1);
                list.add(0, pair);
            }
            return val;
        }
    }

    public static void main(String[] args){
        int[] nums = {3,8,1,9,2,12};
        GetNextWithDuplicateofEvenIndex getNextWithDuplicateofEvenIndex = new GetNextWithDuplicateofEvenIndex(nums);
        int rst = 0;
        while(rst != -1){
            rst = getNextWithDuplicateofEvenIndex.next();
            if(rst != -1){
                System.out.println(rst);
            }
        }
    }

}








Comments

Popular Posts