Re: [問題] 發散數列求最近值~
我終於看懂題目了... 太久沒弄種問答題...Orz
你可能把解題方向弄錯了..
我把題意寫出來...你應該就可以推出答案了..
※ 引述《tonyshan (Iamyourfather)》之銘言:
: 求離70最近的偶數:
: 下面的程式碼是檢查70以下的部分
: 用i減去的方式去解 i到1000以後跳出
: 我寫的方法是
: class Test02{
: int[] array = {0,18,57,75,81};
=> 從這個 array 中找出最接近 70 的數字
: int diff = integer.MAX_VALUE;
=> 這是 upper-bound , 任何數減 70 都不可能大於這個值
=> 記得用 abs, 簡單一些.
: int[] ans = new int[2]; //回答用的數列
=> 答案可能有兩個, Ex: 68, 72 都是最接近 70 的偶數..
當然...如果就這樣 End 有爛尾的嫌疑, 我寫個虛擬碼 你參考看看..
簡化一下, 把 ans 當作一個 queue
for each element, e, in array
if e is an even number
if abs(e-70) <= diff
if ans is full
remove the head element of ans
end if
add e to the tail of ans
diff = abs(e-70)
end if
end if
end for
print out ans
寫完 pesudo code, 我發現這題也沒有那麼表面上看的簡單
的確適合當考題...:P
: -----------------------------------------------
: for(int i = 0;i<diff;i++){
: for(int j = 0;j<array.length;j++){
: if(70-i==array[j]&&(70-i)%2==0){
: ans[0]=array[j];
: }
: }
: if(i>1000) //用i值檢查到1000
: break;
: }
: System.out.println("離70以下離最近的是"+ans[0]);
: 可是這樣寫有一個徵結點就是...
: 當數列裡面沒有0時這個程式碼沒有問題
: 但是遇到數列有0和70以下另一個偶數時會列印出離70最近是0
: 我已經改了一整天沒辦法改出來 感覺好像鬼打牆 越寫越多~
: 版上高手能幫忙回答~謝謝~
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 76.104.157.183
推
07/10 20:22, , 1F
07/10 20:22, 1F
→
07/10 20:24, , 2F
07/10 20:24, 2F
→
07/11 00:47, , 3F
07/11 00:47, 3F
→
07/11 00:49, , 4F
07/11 00:49, 4F
補個說明好了. 用 Mod 就可以簡單實現 queue.
int intdex =0;
.........
ans[index] = e; // even number
index = (index++) % 2;
※ 編輯: byend 來自: 76.104.157.183 (07/11 11:09)
討論串 (同標題文章)