2023华为OD统一考试(A+B卷)题库清单-带答案(持续更新)or2023年华为OD真题机考题库大全-带答案(持续更新)
项目描述:
张兵和王武是五子棋迷,工作之余经常切磋棋艺。这不,这会儿又下起来了。走了一会儿,轮张兵了,对着一条线思考起来了,这条线上的棋子分布如下
用数组表示: -1 0 1 1 1 0 1 01 1
棋子分布说明:
1.-1代表白子,0代表空位,1 代表黑子
2.数组长度L,满足 1 < L < 40,且L为奇数
你得帮他写一个程序,算出最有利的出子位置。最有利定义
1.找到一个空位(0),用棋子(1/-1)填充该位置,可以使得当前子的最大连续长度变大
2.如果存在多个位置,返回最靠近中间的较小的那个坐标;
3.如果不存在可行位置,直接返回-1:
4.连续长度不能超过5个(五字棋约束)
输入描述:
第一行: 当前出子颜色
第二行: 当前的棋局状态
输出描述
1个整数,表示出子位置的数组下标
示例1
输入:
1
-1 0 1 1 1 0 1 0 1 -1 1
输出:
5
说明:
当前为黑子 (1),放置在下标为5的位置,黑子的最大连续长度,可以由3到5
示例2
输入:
-1
-1 0 1 1 1 0 1 0 1 -1 1
输出:
1
说明:
当前为白子,唯一可以放置的位置下标为1,白子的最大长度,由1变为2
示例3
输入:
1
0 0 0 0 1 0 0 0 0 1 0
输出:
5
说明:
可行的位置很多,5最接近中间的位置坐标
public class GoBang {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int chessPieces = Integer.parseInt(sc.nextLine());List<Integer> chessBoard = Arrays.stream(sc.nextLine().split(" ")).map(Integer::parseInt).collect(Collectors.toList());insertPosition(chessPieces,chessBoard);}public static void insertPosition(int chessPieces, List<Integer> chessBoard){//找到空位List<Integer> blank = new LinkedList<>();for (int i = 0; i < chessBoard.size();i++){if (chessBoard.get(i) == 0){blank.add(i);}}//向前、向后遍历连续值(最大连续(靠近中间坐标),长度不超过5)index(blank,chessBoard,chessPieces);}public static void index(List<Integer> blank, List<Integer> chessBoard ,int chessPieces){int middle = chessBoard.size()/2;ChessInfo chess1 = new ChessInfo(-1,-1);for (int i = 0; i < blank.size(); i++){//空白位置插入棋子的连续个数int letf = blank.get(i) - 1;int right = blank.get(i) + 1;int count = 1;Boolean end = true;while (end && letf >= 0 && right <= chessBoard.size() -1){//向前位置遍历if (chessBoard.get(letf) == chessPieces){letf--;count++;continue;}else if (chessBoard.get(right) == chessPieces){//向后遍历right++;count++;continue;}end = false;}//保留最合适的位置 比较连续值,比较离中间位置最近if (chess1.count < count && count <= 5){chess1.count = count;chess1.index = blank.get(i);} else if (chess1.count == count && count <= 5) {if (Math.abs(chess1.index - middle) > Math.abs(blank.get(i) - middle)){chess1.index = blank.get(i);}}}System.out.println(chess1.index);}@Datastatic class ChessInfo{int count;int index;public ChessInfo(int count, int index) {this.count = count;this.index = index;}}
}