Java貪心算法 刪數字問題

問題描述:對給定的n位數字 指定要刪除的數字個數 k ,要求刪除這k個數之後 ,按照數字原左右順序 新形成的數字最大

如輸入: 5689   1    表示對於5689 刪掉一個數字後    得到最大值       

應輸出 : 689


貪心算法核心思想就是 :總是做出當前最好的選擇    

那麼要刪除每一個數時    都從左側第一個數(最高位)開始比較每兩個數字的大小  如果左側小於右側  刪除左側數字    這樣就保證了最高位上的數字總是一直在變大的   


比如  21965 這個數  刪兩位     第一次判斷刪掉1    第二次判斷刪除 2    得到結果最優 


貼出代碼 :

public class 刪數字問題 {


<span style="white-space:pre">	</span>private static int      k;
<span style="white-space:pre">	</span>private static int[]<span style="white-space:pre">	</span>data;
<span style="white-space:pre">	</span>private static int<span style="white-space:pre">	</span>length;


<span style="white-space:pre">	</span>public static void test() {
<span style="white-space:pre">		</span>for (int i = 0; i < k; i++) {
<span style="white-space:pre">			</span>boolean isDelete = false; // 判斷是否可以覆蓋當前數字的標誌量
<span style="white-space:pre">			</span>for (int m = 0; m < length - 1; m++) {
<span style="white-space:pre">				</span>if ((data[m] < data[m + 1]) && !isDelete) {
<span style="white-space:pre">					</span>isDelete = true;
<span style="white-space:pre">				</span>}
<span style="white-space:pre">				</span>if (isDelete) {
<span style="white-space:pre">					</span>data[m] = data[m + 1];
<span style="white-space:pre">				</span>}
<span style="white-space:pre">			</span>}
<span style="white-space:pre">			</span>length--; // 不論這個數是不是在遍歷的時候是否將isDelete變爲true,
<span style="white-space:pre">				</span>      // 循環結束都得將這個長度減1   表示刪去了最後的那個數     
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>for (int n = 0; n < length; n++) {
<span style="white-space:pre">			</span>System.out.print("" + data[n]);
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>public static void main(String[] args) {
<span style="white-space:pre">		</span>data = new int[50];
<span style="white-space:pre">		</span>Scanner in = new Scanner(System.in);
<span style="white-space:pre">		</span>String data1 = in.nextLine();
<span style="white-space:pre">		</span>length = data1.length();
<span style="white-space:pre">		</span>System.err.println("length = " + length);
<span style="white-space:pre">		</span>k = in.nextInt();
<span style="white-space:pre">		</span>String[] data2 = data1.split("");
<span style="white-space:pre">		</span>for (int j = 0; j < length; j++) {
<span style="white-space:pre">			</span>data[j] = Integer.parseInt(data2[j]);
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>test();
<span style="white-space:pre">		</span>in.close();


<span style="white-space:pre">	</span>}
}


輸入的是一個String    然後split  分割成String數組      然後 轉爲int[] 數組     用全局保存

刪除k 個數  就建立一個 for循環,次數爲k

內層循環爲了遍歷這個數    需要注意的是每次循環結束都需要  刪去最後的數字   就是length--  ;

length是我設置的全局int  表示當前數組的長度   




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章