2018年5月27日 星期日

[Codility] 第六課 Distinct



寫一個 function


class Solution { public int solution(int[] A); }

陣列 A 有連續好幾個 整數 N,最後返回不重複的整數數量。

舉例來說,有一個 陣列 A

A[0] = 2 A[1] = 1 A[2] = 1 A[3] = 2 A[4] = 3 A[5] = 1
此 function 返回 3,因為在陣列 A裡面有 1, 2, 3 三個不重複的數字。

條件:

  • N的範圍必須是 0~100,000
  • 陣列 A 每個元素範圍 -1000,000 ~ 1000,000

複雜度:

  • 最糟的時間複雜度為 O(N * log(N))
  • 最糟的空間複雜度為 O(N) (不含 input 的參數)


Java 程式碼
  1. // you can also use imports, for example:
  2. // you can also use imports, for example:
  3. import java.util.*;
  4.  
  5. // you can write to stdout for debugging purposes, e.g.
  6. // System.out.println("this is a debug message");
  7.  
  8. class Solution {
  9. public int solution(int[] A) {
  10. // write your code in Java SE 8
  11. HashSet<Integer> set = new HashSet<Integer>();
  12. for(int i = 0;i < A.length; i++){
  13. if(!set.contains(A[i])){
  14. set.add(A[i]);
  15. }
  16. }
  17. return set.size();
  18. }
  19. }

分數共拿 100%
任何問題歡迎交流討論,一起學習!

更多面試相關

⇒ [Codility] 面試寫題目經驗感想


感謝相關連結
https://www.codility.com/
https://app.codility.com/programmers/lessons/6-sorting/distinct/

2 則留言:

  1. 用HashSet就不會重複了,前面不需要sort,你的那一行是多的

    回覆刪除