题目
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;
}
};