[1/30] MIOJ刷题:和为零的三元组/数独游戏

  1. 和为零的三元组
    地址:MIOJ 15. 和为零的三元组
package lambdasinaction.playground.mioj;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author li2niu
 * @date 2020/10/21
 * @Description
 */


public class TriElementsEquals0 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String line;
        while (scan.hasNextLine()) {
            line = scan.nextLine().trim();
            List<Integer> elements = Arrays.stream(line.split(",")).map(Integer::parseInt).collect(Collectors.toList());
            int size = elements.size();
            if (size < 3) {
                System.out.println(0);
                return;
            }
            Set<String> answerSetList = new HashSet<>();
            getAnswer1(answerSetList, elements);
            System.out.println(answerSetList.size());

            Set<String> answerSetList2 = new HashSet<>();
            getAnswer2(answerSetList2, elements);
            System.out.println(answerSetList2.size());


        }
    }

    /**
     * 先确定中间的数字,然后两边的数字左右移动调节寻找符合条件的三元组
     * O(n^2)
     * @param answerSetList
     * @param elements
     */
    private static void getAnswer1(Set<String> answerSetList, List<Integer> elements) {
        int maxIndex, minIndex;
        List<Integer> sortedList = elements.parallelStream().sorted().collect(Collectors.toList());
        int size = sortedList.size();
        for (int i = 1; i < size - 1; i++) {
            minIndex = i - 1;
            maxIndex = i + 1;
            while (minIndex >= 0 && maxIndex < size) {
                int sum = sortedList.get(i) + sortedList.get(minIndex) + sortedList.get(maxIndex);
                if (sum == 0) {
                    String result = sortedList.get(minIndex) + "," + sortedList.get(i) + "," + sortedList.get(maxIndex);
                    answerSetList.add(result);
                    minIndex--;
                } else if (sum > 0) {
                    minIndex--;
                } else {
                    maxIndex++;
                }
            }
        }
    }

    /**
     * 枚举所有的组合然后寻找符合条件的三元组
     * O(n*(n-1)*(n-2))=> O(n^3)  (*☻-☻*))
     * @param answerSetList
     * @param elements
     */
    private static void getAnswer2(Set<String> answerSetList, List<Integer> elements) {
        int size = elements.size();
        for (int i = 0; i < size; i++) {
            Integer element = elements.get(i);
            Queue<Integer> queue = new LinkedList<>();
            for (int j = 0; j < size; j++) {
                if (j != i) {
                    queue.add(elements.get(j));
                }
            }
            Integer pop1;
            int poll1Count = 0;
            while (poll1Count <= queue.size() && (pop1 = queue.poll()) != null) {
                poll1Count++;
                Integer pop2;
                int poll2Count = 0;
                while (poll2Count <= queue.size() - 1 && (pop2 = queue.poll()) != null) {
                    poll2Count++;
                    if (pop1 + pop2 + element == 0) {
                        String result = Stream.of(pop1, element, pop2)
                                .sorted()
                                .map(String::valueOf)
                                .collect(Collectors.joining(","));
                        answerSetList.add(result);
                    }
                    queue.add(pop2);
                }
                queue.add(pop1);
            }
        }
    }
}

  1. 数独游戏
    地址:MIOJ 45.数独游戏
    leetcode Valid sudoku
    这题有错误
    leetcode版本
package playground.leetcode.sudoku;

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

/**
 * @author lichuanyi
 * @date 2020/10/22
 * @Description
 */
public class Solution {
    private static final String case1 = "8,3,.,.,7,.,.,.,. 6,.,.,1,9,5,.,.,. .,9,8,.,.,.,.,6,. 8,.,.,.,6,.,.,.,3 4,.,.,8,.,3,.,.,1 7,.,.,.,2,.,.,.,6 .,6,.,.,.,.,2,8,. .,.,.,4,1,9,.,.,5 .,.,.,.,8,.,.,7,9";
    private static final String case2 = "5,3,.,.,7,.,.,.,. 6,.,.,1,9,5,.,.,. .,9,8,.,.,.,.,6,. 8,.,.,.,6,.,.,.,3 4,.,.,8,.,3,.,.,1 7,.,.,.,2,.,.,.,6 .,6,.,.,.,.,2,8,. .,.,.,4,1,9,.,.,5 .,.,.,.,8,.,.,7,9";
    private static final String case3 = ".,.,.,.,5,.,.,1,. .,4,.,3,.,.,.,.,. .,.,.,.,.,3,.,.,1 8,.,.,.,.,.,.,2,. .,.,2,.,7,.,.,.,. .,1,5,.,.,.,.,.,. .,.,.,.,.,2,.,.,. .,2,.,9,.,.,.,.,. .,.,4,.,.,.,.,.,.";

    private static final String case4 = "5,3,.,.,7,.,.,.,. 6,.,.,1,9,5,.,.,. .,9,8,.,.,.,.,6,. 8,.,.,.,6,.,.,.,3 4,.,.,8,.,3,.,.,1 7,.,.,.,2,.,.,.,6 .,6,.,.,.,.,2,8,. .,.,.,4,1,9,.,.,5 .,.,.,.,8,.,.,7,9";

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String line;
        while (scan.hasNextLine()) {
            line = scan.nextLine().trim();
            String[] sudokuLines = line.split(" ");

            char[][] board = initBoard(sudokuLines);
            printBoard(board);
            System.out.println(new Solution().isValidSudoku(board));
        }
    }

    private static void printBoard(char[][] board) {
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                System.out.print(board[i][j]+" ");
            }
            System.out.println();
        }
    }

    private static char[][] initBoard(String[] sudokuLines) {
        char[][] board = new char[9][9];
        for (int i = 0; i < 9; i++) {
            String line = sudokuLines[i];
            final String[] stones = line.split(",");
            for (int j = 0; j < 9; j++) {
                board[i][j] = ".".equals(stones[j]) ? '.' : stones[j].charAt(0);
            }
        }
        return board;
    }

    public boolean isValidSudoku(char[][] board) {
        Map<Character, Integer> map = new HashMap<>(9);
        boolean result = validateRows(board, map);
        if (!result) {
            return false;
        }
        map.clear();
        result = validateColumns(board, map);
        if (!result) {
            return false;
        }
        map.clear();
        result = validate9Cells(board, map);
        return result;
    }

    private boolean validateRows(char[][] board, Map<Character, Integer> map) {
        for (int i = 0; i < 9; i++) {
            map.clear();
            for (int j = 0; j < 9; j++) {
                if (map.containsKey(board[i][j])) {
                    return false;
                }
                if (board[i][j] != '.') {
                    map.put(board[i][j], 0);
                }
            }
        }
        return true;
    }

    /**
     * 校验九个小方格
     *
     * @param board
     * @param map
     */
    private static boolean validate9Cells(char[][] board, Map<Character, Integer> map) {
        for (int i = 0; i < 3; i++) {
            for (int l = 0; l < 3; l++) {
                map.clear();
                for (int j = 0; j < 3; j++) {
                    for (int k = 0; k < 3; k++) {
                        char stone = board[i * 3 + j][3*l+k];
                        if (map.containsKey(stone)) {
                            return false;
                        }
                        if (stone != '.') {
                            map.put(stone, 0);
                        }
                    }
                }
            }

        }
        return true;
    }

    /**
     * 校验列
     *
     * @param board
     * @param map
     */
    private static boolean validateColumns(char[][] board, Map<Character, Integer> map) {
        for (int i = 0; i < 9; i++) {
            map.clear();
            for (int j = 0; j < 9; j++) {
                char stone = board[j][i];
                if (map.containsKey(stone)) {
                    return false;
                }
                if (stone != '.') {
                    map.put(stone, 0);
                }
            }
        }
        return true;
    }

    /**
     * 初始化棋盘同时按行校验
     *
     * @param sudokuLines
     * @param map
     * @return
     */
    private static int[][] initBoardAndValidateRows(String[] sudokuLines, Map<Integer, Integer> map) {
        int[][] board = new int[9][9];
        for (int i = 0; i < 9; i++) {
            String line = sudokuLines[i];
            final String[] stones = line.split(",");
            map.clear();
            for (int j = 0; j < 9; j++) {
                board[i][j] = "-".equals(stones[j]) ? 0 : Integer.parseInt(stones[j]);
                if (map.containsKey(board[i][j])) {
                    System.out.println(false);
                    return new int[0][];
                }
                if (board[i][j] != 0) {
                    map.put(board[i][j], 0);
                }
            }
        }
        return board;
    }
}

mioj版本

package playground.mioj.day1.sudoku;

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

/**
 * @author: lichuanyi
 * @description:
 * @date: 2020/10/21 23:35
 */
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String line;
        while (scan.hasNextLine()) {
            line = scan.nextLine().trim();
            String[] sudokuLines = line.split(" ");
            Map<Integer,Integer> map = new HashMap<>(9);
            int[][] board = initBoardAndValidateRows(sudokuLines,map);
            if (board.length == 0){
                return;
            }
//            else{
//                for (int i = 0; i < 9; i++) {
//                    for (int j = 0; j < 9; j++) {
//                        System.out.print(board[i][j]+" ");
//                    }
//                    System.out.println();
//                }
//            }
            map.clear();
            boolean result = validateColumns(board,map);
            if (!result){
                System.out.println(false);
                return;
            }
            map.clear();
            result = validate9Cells(board,map);
            System.out.println(result);
        }
    }

    /**
     * 校验九个小方格
     * @param board
     * @param map
     */
    private static boolean validate9Cells(int[][] board, Map<Integer, Integer> map) {
        for (int i = 0; i < 3; i++) {
            for (int l = 0; l < 3; l++) {
                map.clear();
                for (int j = 0; j < 3; j++) {
                    for (int k = 0; k < 3; k++) {
                        int stone = board[i*3+j][l*3+k];
                        if (stone!= 0 && map.containsKey(stone)){
                            return false;
                        }
                        map.put(stone,0);
                    }
                }
            }

        }
        return true;
    }

    /**
     * 校验列
     * @param board
     * @param map
     */
    private static boolean validateColumns(int[][] board, Map<Integer, Integer> map) {
        for (int i = 0; i < 9; i++) {
            map.clear();
            for (int j = 0; j < 9; j++) {
                int stone = board[j][i];
                if (stone != 0 && map.containsKey(stone)){
                    return false;
                }
                map.put(stone,0);
            }
        }
        return true;
    }

    /**
     * 初始化棋盘同时按行校验
     * @param sudokuLines
     * @param map
     * @return
     */
    private static int[][] initBoardAndValidateRows(String[] sudokuLines, Map<Integer, Integer> map) {
        int[][] board = new int[9][9];
        for (int i = 0; i < 9; i++) {
            String line = sudokuLines[i];
            final String[] stones = line.split(",");
            map.clear();
            for (int j = 0; j < 9; j++) {
                board[i][j] = "-".equals(stones[j]) ? 0 : Integer.parseInt(stones[j]);
                if (board[i][j]!= 0 && map.containsKey(board[i][j])){
                    System.out.println(false);
                    return new int[0][];
                }
                map.put(board[i][j],0);
            }
        }
        return board;
    }
}


//5,1,-,6,-,-,-,9,8 -,7,-,1,9,4,-,-,- -,-,-,-,-,-,-,6,- 8,-,-,4,-,-,7,-,- -,6,-,8,-,3,-,2,- -,-,3,-,-,1,-,-,6 -,3,-,-,-,-,-,4,- -,-,-,3,1,9,-,8,- 2,8,-,-,-,5,-,7,9

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,080评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,422评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,630评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,554评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,662评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,856评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,014评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,752评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,212评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,541评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,687评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,347评论 4 331
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,973评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,777评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,006评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,406评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,576评论 2 349