int[][] grid = new int[3][4]
grid
0 -> 0, 0, 0, 0
1 -> 0, 0, 0, 0
2 -> 0, 0, 0, 0int[][] grid = new int[3][] : 행(row)만 선언되어 열(col)에 대한 것을 추가로 선언해야함
grid[0] = new int[1];
grid[1] = new int[4];
0 -> 0
1 -> 0, 0, 0, 0
- Array -> List
- List -> Array
- 2차원 Array -> List<List< Integer>>
- List<List< Integer>> -> 2차원 Array
Array : fixed(고정)값이라서 변경 불가, List : flexible하여 언제든지 변경 가능
public static List<Integer> covertArrayToList(int[] nums) {
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < nums.length; i++) {
result.add(nums[i]);
}
return result;
}
public static int[] covertListToArray(List<Integer> list) {
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
public static List<List<Integer>> convertArrayToList(int[][] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
for (int i = 0; i < nums.length; i++) {
List<Integer> list = new ArrayList<Integer>();
for (int j = 0; j < nums[i].length; j++) {
list.add(nums[i][j]);
}
result.add(list);
}
return result;
}
public static int[][] covertListToArray(List<List<Integer>> list) {
int[][] result = new int[list.size()][];
// 열(col)부분을 선언 (필수)
for (int i = 0; i < result.length; i++) {
result[i] = new int[list.get(i).size()];
}
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.get(i).size(); j++) {
result[i][j] = list.get(i).get(j);
}
}
return result;
}
주어진 행렬 M x N에서 요소가 0인 경우 그 0이 속한 행과 열의 모든 요소를 0으로 설정
Input : {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}
Output : {{1, 0, 1}, {0, 0, 0}, {1, 0, 1}}
HashSet을 이용하는 이유는 중복된 값을 없애기 위함
import java.util.*
public class Q4 {
public static void main(String[] args) {
int[][] matrix = { { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 } };
solve(matrix);
print(matrix);
}
public static void solve(int[][] matrix) {
Set<Integer> rowSet = new HashSet<>();
Set<Integer> colSet = new HashSet<>();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == 0) {
rowSet.add(i);
colSet.add(j);
}
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (rowSet.contains(i) || colSet.contains(j)) {
matrix[i][j] = 0;
}
}
}
}
public static void print(int[][] grid) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.print(" [" + i + "][" + j + "] " + grid[i][j]);
}
System.out.println();
}
}
}
인프런 강의 : 코딩테스트 전 꼭 알아야 할 개념과 문제(with 자바) - 푸샵맨 코딩스터디