Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions DisappearedNumbers1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

import java.util.ArrayList;
import java.util.List;

/**
* url: https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
* Title: 448. Find All Numbers Disappeared in an Array Time Complexity:
* O(n) Space Complexity: O(1)
*/
public class DisappearedNumbers1 {

public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> mList = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int pos = Math.abs(nums[i]) - 1;
if (nums[pos] > 0) {
nums[pos] = -nums[pos];
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
mList.add(i + 1);
}
}
return mList;
}

public static void main(String[] args) {
List<Integer> missing = new DisappearedNumbers1().findDisappearedNumbers(new int[]{4, 3, 2, 7, 8, 2, 3, 1});
System.out.println(missing);

missing = new DisappearedNumbers1().findDisappearedNumbers(new int[]{10,2,5,10,9,1,1,4,3,7});
System.out.println(missing);
}
}
69 changes: 69 additions & 0 deletions GameOfLife.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/**
* url: https://leetcode.com/problems/game-of-life/
* Title: 289. Game of Life
* Time Complexity: O(m*n)
* Space Complexity: O(1)
*/
public class GameOfLife {

int moves[][] = {{0, 1}, {0, -1}, {1, 0,}, {-1, 0}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}};
// moves in all eight directions.

public void gameOfLife(int[][] board) {
int m = board.length;
int n = board[0].length;

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int alivecount = 0;
for (int[] move : moves) {
int x = i + move[0];
int y = j + move[1];
if (x >= 0 && x < m && y >= 0 && y < n) {
if (board[x][y] == 1 || board[x][y] == 2) { // 2 for mar gaya but alive in original state
alivecount++;
}
}
}
if (board[i][j] == 1 || board[i][j] == 3) {
if (alivecount > 3) { // overpopulation
board[i][j] = 2; // 2 for mar gaya
}
if (alivecount < 2) { // underpopulation
board[i][j] = 2; // 2 for mar gaya
}
if (alivecount == 2 || alivecount == 3) { // underpopulation
board[i][j] = 1; // alive
}
}
if (board[i][j] == 0) {
if (alivecount == 3) {
board[i][j] = 3; // 3 for new born
}
}

}
}
}

public static void main(String[] args) {
int[][] board = {{0, 1, 0}, {0, 0, 1}, {1, 1, 1}, {0, 0, 0}};
new GameOfLife().gameOfLife(board);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == 2) {
board[i][j] = 0;
}
if (board[i][j] == 3) {
board[i][j] = 1;
}
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
}