LintCode--first unique number in stream

题目

Given a continuous stream of numbers, write a function that returns the first unique number whenever terminating number is reached(include terminating number). If there no unique number before terminating number or you can't find this terminating number, return -1.

样例

Given a stream [1, 2, 2, 1, 3, 4, 4, 5, 6] and a number 5
return 3

Given a stream [1, 2, 2, 1, 3, 4, 4, 5, 6] and a number 7
return -1

思路

1、将整型数组转换成集合al,不要使用Arrays.asList(),因为数组中的数据是基本数据类型int,如果直接转成集合,集合中的元素类型是数组类型int[],所以应该自己创建一个集合,然后遍历数组,将数组的值存到集合中。然后使用contains()方法判断是否存在terminating number,如果不存在,就直接返回-1,如果存在,跳到2步;
2、使用集合的indexOf()查找terminating number第一次出现的角标index,判断index是否为0,如果是0,那么返回-1,如果不是0,则使用al.subList(0, index)取出子集合list,子集合中就是需要查找的范围;
3、遍历子集合中的数值,并将数值和角标存到HashMap集合中,如果有重复的数值,其角标值为最后一次出现的角标。
4、重新遍历子集合list,对于角标i的元素,看其在HashMap集合中对应的值,如果和i相同,就说明不是重复元素,返回该数值,如果和i不相同,说明有重复的数值,就需要将HashMap集合中对应的值变成i,这样在遍历之后的重复数值时,就不会返回错误值了。如果遍历结束都没有返回值,那就返回-1.

代码

public class Solution {
    /*
     * @param : a continuous stream of numbers
     * @param : a number
     * @return: returns the first unique number
     */
    public int firstUniqueNumber(int[] nums, int number) {
        // Write your code here
        ArrayList<Integer> al = new ArrayList<Integer>();
        for(int i = 0; i < nums.length; i++)
        {
            al.add(nums[i]);
        }
        
        if(al.contains(number))
        {
            int index = al.indexOf(number);
            if(index != 0)
            {
                List<Integer> list = al.subList(0, index);
                HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
                
                for(int i = 0; i < list.size(); i++)
                {
                    hm.put(list.get(i), i);
                }
                
                for(int i = 0; i < list.size(); i++)
                {
                    if(i == hm.get(list.get(i)))
                    {
                        return list.get(i);
                    }
                    else
                    {
                        hm.put(list.get(i), i);
                    }
                }
            }
        }
        
        return -1;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值