HDU2020——绝对值排序(java实现,使用map)

Question Description

 Input

Output

Sample Input

Sample Output

解题思路简述:

在接收每一个数组的过程中,将负数及其绝对值以键值对的形式存入map(先绝对值,后负数)(因为题目有说“题目保证对于每一个测试实例,所有的数的绝对值都不相等。”)

然后数组中实际存储的是绝对值而不是负数

然后将数组通过冒泡排序降序排序

最后遍历数组,同时查询map中是否有相应键值对,有的话就将该项变为负数

然后打印_完成

源码:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main{
    static void bubble_decending_order(int[] arr){
        boolean flag = true;
        for(int i =1;i<arr.length;++i){
            for(int j=0;j<arr.length-i;++j){
                if(arr[j]<arr[j+1]){
                    flag = false;
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
            if(flag){
                break;
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(true){
            int count = sc.nextInt();
            if(count==0) break;
            int[] data = new int[count];
            Map<Integer,Integer> map = new HashMap<>();
            for(int i = 0;i<count;++i){
                data[i] = sc.nextInt();
                if(data[i]<0)
                    map.put(Math.abs(data[i]),data[i]);
                data[i] = Math.abs(data[i]);
            }
            bubble_decending_order(data);
            for(int i = 0;i<data.length;++i){
                if(map.containsKey(data[i])){
                    data[i] = map.get(data[i]);
                }
            }
            for(int i = 0;i<data.length;++i){
                System.out.print(data[i]);
                if(i+1!=data.length)
                    System.out.print(" ");
            }
            System.out.println();

        }
    }
}

hdoj已通过

希望对大家有所帮助

以上

猜你喜欢

转载自www.cnblogs.com/lavender-pansy/p/12129236.html