![](/img/trans.png)
[英]Find Two elements in the Array that add up to the Target number in O(n * log n) Time
[英]Add n number of integers in array to get a target number in Java?
數組作為用戶的輸入。 該數組包含整數。 加一些,全部或僅一個就足夠了,以使總和盡可能接近100。
我的問題是我真的不知道如何處理循環。 我已經嘗試過嵌套兩個,但是我不知道計算數組可能需要多少個整數,這很棘手。
到目前為止,我的循環會循環每個整數:
//looping over all integers in the array
for (int i = 0; i < myArray.length; i++) {
//check already here if it is close to 100?
//compare the integer above to the next
for (int j = i + 1; nextWeight < myArray.length; j++) {
//the results should be saved temporary to comparision to new sums
}
}
我知道這並不多,而且我知道它可能以某種方式涉及動態編程。
有沒有人對我有幫助?
根據我對您問題的解釋,您最大的問題就在於算法。 您應該首先確定算法,然后再進行編碼。 如果我想按照您的要求做,我會先對數組進行升序或降序排序。 有很多排序算法。 但是,我認為您正在查看的是子集和問題,可以通過遞歸二叉樹遍歷算法解決。 我不會給您代碼,但是如果您有時間研究它,它將可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.