算法學習——貪心算法之刪數字(求最小值)

算法描述

在給定的n位數字,刪除其中的k位數字( k < n),使得最後的n-k爲數字爲最小值(原次序不變)算法

算法思路

  1. 考慮到是要移出數字,咱們使用鏈表設計此算法較爲方便,鏈表能夠直接移出某個位置的元素設計

  2. 使用貪心算法,每一步都要達到最優3d

  3. 從最高位開始,若下一位比上一位要小,則將上一位的數字移出,結束以後再次從最高位開始code

這裏須要注意,會有特例blog

當輸入從小到大的的一個數的時候,上述算法將會沒法運行,好比123456,刪除1個數字變爲最小,咱們把6刪去,這樣纔是最小的(即從末尾刪除數字)ci

算法實現

Scanner scanner = new Scanner(System.in);
    System.out.println("請輸入整數:");
    String s = scanner.nextLine();
    System.out.println("刪除數字的個數:");
    int n = scanner.nextInt();
    scanner.close();
    
    int a[] = new int[s.length()];
    
    for(int i=0;i<s.length();i++){
        char temp =s.charAt(i);
        a[i] = temp -'0';//不減去‘0’則會得到Ascii碼 
    }
    

    
    LinkedList<Integer> linkedList = new LinkedList<Integer>();
    for(int i=0;i<a.length;i++){
        linkedList.add(a[i]);
    }
    
    int flag =0;
    while(flag<n){
        for(int i=0;i<linkedList.size()-1;i++){
            if(linkedList.get(i)>linkedList.get(i+1)){
                linkedList.remove(i);//使用鏈表移出元素
                flag++;
                
                break;//結束本次循環,跳轉到while循環中
            }
            //考慮到特殊狀況,當遍歷徹底部數字都不知足條件,從末尾刪除數字
            if(i==linkedList.size()-2){
                linkedList.removeLast();
                flag++;
            
            }
        }
    }
    
    System.out.print("截取的"+n+"個數字後的最小值爲");
    for(int i=0;i<linkedList.size();i++){
        
        System.out.print(linkedList.get(i));
    }

結果

相關文章
相關標籤/搜索