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
.
样例
View Code
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 class Solution { 2 public: 3 /* 4 * @param : a continuous stream of numbers 5 * @param : a number 6 * @return: returns the first unique number 7 */ 8 int firstUniqueNumber(vector<int> nums, int number) { 9 // Write your code here 10 bool flag = false; 11 int pos = 0; //用来记录number的位置 12 for (int i = 0; i < nums.size(); i++) { 13 pos++; 14 if (number == nums[i]) { 15 flag = true; 16 break; 17 } 18 } 19 if (flag == false) return -1; 20 21 map<int, int> s; 22 for (int i = 0; i < pos; i++) { 23 s[nums[i]]++; 24 } 25 for (int i = 0; i < pos; i++) { 26 if (s[nums[i]] == 1) { 27 return nums[i]; 28 } 29 } 30 return -1; 31 } 32 };