數據表記錄包含表索引和數值(int范圍的整數),請對表索引相同的記錄進行合並,即將相同索引的數值進行求和運算,輸出按照key值升序進行輸出


此題如果直接使用有序的TreeMap就不需要這樣折騰:
1.map的key值唯一性,故就不在需要set集合來去重
2.使用map后利用key的唯一性,把序列號相同的數據直接加在一起,代碼會很簡潔

package com.pagination.plus.workTrain;

import com.alibaba.fastjson.JSON;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;

public class Main3 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner in = new Scanner(new FileInputStream("D:\\JavaData\\tmp/input.txt"));
        //Scanner in = new Scanner(System.in);

        while (in.hasNext()) {//注意while處理多個case
            String strNum = in.nextLine();
            int count = Integer.parseInt(strNum);
            int[] k = new int[count];
            int[] v = new int[count];

            for (int i = 0; i < count; i++) {
                String[] value = in.nextLine().split(" ");
                //System.out.println(JSON.toJSONString(value));
                k[i] = Integer.parseInt(value[0]);
                v[i] = Integer.parseInt(value[1]);
            }

            Set<Integer> set = new HashSet<>();//相同的索引值只統計一次
            Map<Integer,Integer> contents = new HashMap<>();//便於排序后輸出
            List<Integer> key = new ArrayList<>();
            //List<Integer> val = new ArrayList<>();

            //Map<Integer,Integer> map00 = new TreeMap<>();

            for (int i = 0; i < count; i++) {
                if (set.add(k[i])) {
                    int tmpVal = v[i];
                    for (int j = 0; j < count; j++) {
                        if ((i != j) && (k[i] == k[j])) {
                            tmpVal += v[j];

                        }
                    }
                    key.add(k[i]);
                    //val.add(tmpVal);
                    contents.put(k[i],tmpVal);
                    //map00.put(k[i],tmpVal);
                    //System.out.println(k[i] + " " + tmpVal);
                }
            }
            //或者使用有序的TreeMap
            //System.out.println(JSON.toJSONString(map00));
            //排序
            key.sort(Integer::compareTo);
            //key.forEach(System.out::print);
            for(int i=0;i<key.size();i++){
                int index = key.get(i);
                System.out.println(index+" "+contents.get(index));
            }





        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM