2013-02-27 25 views
0

增加一個陣列得到我需要讓我不能加入陣列的不同號碼來獲得一個最小數量。基本上如果我有這些數字:1,1,1,5;我可以得到1,2,3,5,6 ...但我不能得到4,所以這是我正在尋找的數字。現在,這是我的代碼:數字我可以在java中

import java.util.Scanner; 
public class Broj_6 { 

public static void main(String[] args) { 
    Scanner unos = new Scanner(System.in); 
    int k; 
    int n = unos.nextInt(); 
    int niz []= new int [n]; 
    for(int i = 0;i<n;i++){ 
     niz[i]=unos.nextInt(); 
    } 
    BubbleSort(niz); 
    for(int i = 0;i<n;i++){ 
     System.out.print(niz[i] + " "); 
    } 
    for(int br = 1;br<=10000;br++){ 
     for(k = 1;k<n;k++){ 
      if(niz[k]>br){ 
       break; 
      } 
     } 
     int podniz [] = new int [k]; 
     for(int i=0;i<podniz.length;i++){ 
      niz[i] = podniz[i]; 
     } 
     //This is where I will need my logic to go 
    } 
} 

static void BubbleSort (int [] niz){ 
    int pom; 
    for(int i = 0;i<niz.length-1;i++){ 
     for(int j = 0;j<niz.length-1-i;j++){ 
      if(niz[j]>niz[j+1]){ 
       pom = niz[j]; 
       niz[j] = niz[j+1]; 
       niz[j+1] = pom; 
      } 
     } 
    } 
} 
} 

因此,代碼的推移,從1單獨測試每個號碼100000,原本小於數字本身給出的所有數字的一個子。現在是這個問題,我不知道如何混合和匹配子數組中的數字,以便它可以得到(或不能獲得)所需的數字。當每個組合都經過測試並且沒有想要的數字時,我會打破;循環和印刷我。只是爲了澄清,我只能用另外,每個數字只能進去一次

回答

0

你可以如下做到這一點: 使用兩個嵌套的循環,就像下面來計算不同數量的總和:

List<Integer> additionList = new ArrayList<Integer>(); 
int []inputNumbers = .... // Logic to read inputs 
for(int _firstIndex = 0; _firstIndex < totalInputs; _firstIndex++){ 
    for(int _secondIndex = _firstIndex + 1; _secondIndex < totalInputs; _secondIndex++){ 
     additionList.add(inputNumbers[_firstIndex]); // only because you have 1 in the sample output 
     additionList.add(inputNumbers[_firstIndex] + inputNumbers[_secondIndex ]); 
    } 
} 

然後排序additionList並查找任何缺少的條目。第一個欠缺的出入將是你的答案,

0

排序整個數組,然後找出所有子陣列並解決問題的總和,但昂貴:O(2N^2)〜O(N^2)。

解決這個更有效的方法將是Kadane的算法:http://en.wikipedia.org/wiki/Maximum_subarray_problem

什麼算法中的作用:從 第一個元素開始,增加數組的大小(子陣列),直到你達到你希望的總和。

my_num = 1; 
while(true){ 
    if(sum_subarray) > my_num){ 
    current position = new subarray; 
} 

這個子陣概念是通過Kadane的方法計算:

def sum_subarray(A): 
sum_ending_here = sum_so_far = 0 
for x in A: 
    sum_ending_here = max(0, max_ending_here + x) 
    sum_so_far = max(sum_so_far, sum_ending_here) 
return sum_so_far 

我不能徹底解決問題。這裏提到的'my_num'需要從1遞增,並在my_num > max_sum時中斷。我希望有人可以添加並編譯它。

注:

這也將照顧如果負元素存在於陣列。

相關問題