LeetCode - Maximum Swap
Question Definition
Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
More …Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
More …Design a data structure that supports all following operations in average O(1) time.
According to the Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.”
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
**Follow up: **
public void gameOfLife(int[][] board) {
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[i].length; j++){
int neighbors = 0;
if(i > 0 && Math.abs(board[i - 1][j]) == 1)
neighbors++;
if(j > 0 && Math.abs(board[i][j - 1]) == 1)
neighbors++;
if(i > 0 && j > 0 && Math.abs(board[i - 1][j - 1]) == 1)
neighbors++;
if(i > 0 && j < board[i].length - 1 && Math.abs(board[i - 1][j + 1]) == 1)
neighbors++;
if(j < board[i].length - 1 && Math.abs(board[i][j + 1]) == 1)
neighbors++;
if(i < board.length - 1 && j < board[i].length - 1 && Math.abs(board[i + 1][j + 1]) == 1)
neighbors++;
if(i < board.length - 1 && j > 0 && Math.abs(board[i + 1][j - 1]) == 1)
neighbors++;
if(i < board.length - 1 && Math.abs(board[i + 1][j]) == 1)
neighbors++;
if(Math.abs(board[i][j]) == 1){
if(neighbors < 2 || neighbors > 3)
board[i][j] = -1;
} else {
if(neighbors == 3)
board[i][j] = -2;
}
}
}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[i].length; j++){
if(board[i][j] == -1)
board[i][j] = 0;
else if(board[i][j] == -2)
board[i][j] = 1;
}
}
}
A peak element is an element that is greater than its neighbors.
More …Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
More …