LintCode--first unique number in stream__java

來源:互聯網
上載者:User
題目

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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.