尋找zero組數

題目描述:
給定一個整數的數組,找出其中的pair(a,b),使得a+b=0,並返回這樣的pair數目。(a,b)和(b,a)是同一組。
輸入:
整數數組
輸出
找到的pair數目
樣例輸入
-1,2,4,5,-1
樣例輸出
1
思路:
找到數組中的和爲0的兩個數,將其保存在map中,根據題目要求,[1,-1]和[-1,1]這樣的算是一種,所以需要map的一份拷貝數據,如果map中存在一個key是另外一個value的情況,將拷貝的map中的內容刪除一個即可。


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

public class Test1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()){
            String s = sc.nextLine();
            String ss = s.replaceAll(" ","");
            String[] temp = ss.trim().split(",");
            long[] array = new long[temp.length];
            for (int i = 0; i < array.length; i++) {
                array[i] = Integer.parseInt(temp[i]);
            }
            System.out.println(getResult(array));
        }
    }
    public static long getResult(long[] array){

        Map<Long, Long> map = new HashMap<>();
        for (int i = 0; i < array.length; i++) {
            for (int j = i; j < array.length; j++) {
                if(array[i] + array[j] == 0 &&!map.containsKey(array[i])&&!map.containsKey(array[j])){
                    map.put(array[i],array[j]);
                }
            }
        }
        Map<Long,Long> hashmap = new HashMap<>();
        for (Long key : map.keySet()) {
            hashmap.put(key,map.get(key));
        }
        for (Long key : map.keySet()) {
            if(map.containsKey(map.get(key))&&hashmap.containsKey(map.get(key))){
                hashmap.remove(key);
            }
        }
        return hashmap.size();
    }
}

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