題目
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(),因為數組中的資料是基礎資料型別 (Elementary Data Type)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; }};