2015-09-30 66 views
-3

我正在寫一個函數使用java語言,它接受一維數組和數組的大小作爲函數的輸入。我想知道數組中有多少個函數值。我將如何做到這一點?JAVA中的數組,重複?

+2

一種選擇,它不需要使用除數組以外的任何數據結構,將第一_sort_陣列,和第二到遍歷數組,每次創建新值時增加一個計數器。 –

+1

另一種選擇是,如果你可以使用更奇特的數據結構,那就是使用地圖並遍歷數組一次,爲每個數字插入相同的值。然後,您可以簡單地檢查地圖中的_number_個鍵,這是不同值的數量。 –

+2

爲什麼你編輯這個問題,以便沒有人能看到它是什麼? – Domysee

回答

1
#Find unique items from array: 
1. Create one new array 
2. Take each item from existing array 
3. Check if the item is exist in new array 
4. **If not exist push the item into new array** else go for next item 
5. After iterating all item in array get the length of new array 
+0

我們將如何檢查來自現有數組的項目是否在新數組中? –

+0

直截了當的是,從新數組中獲取每個項目並將其與現有數組中的當前項目進行比較。 – Dipak

2

方法1(O(nlogn)):

  1. 排序陣列。
  2. 比較數組中的相鄰元素
  3. 每當相鄰元素不相等時增加計數。請使用額外變量來照顧三個連續的相同元素。

方法2(O(n)的但空間的爲O(n)複雜性):

  1. 爲值創建哈希表。
  2. 如果不存在於散列表中,則插入一個值。
  3. 計數和在打印值用於本哈希表
+1

散列太複雜。我會創建一個左值節點值較小的二叉樹,右值節點值較大。無需處理散列衝突;可管理的空間和時間要求。 – Jens

0
#include <stdio.h> 

int main() 
{ 
    int n[10] = {1,2,5,5,3,4,1,4,5,11}; 
    int count = 0; int i = 0; 
    for (i=0; i< 10; i++) 
    { 
     int j; 
      for (j=0; j<i; j++) 
       if (n[i] == n[j]) 
       break; 
      if (i == j) 
       count += 1; 
    } 

    printf("The counts are: %d distinct elements", count); 

    return 0; 
} 
+0

謝謝,是的,我用另一種方法。 –