|
| 1 | +package arrays3; |
| 2 | + |
| 3 | +import java.util.HashSet; |
| 4 | +import java.util.Set; |
| 5 | + |
| 6 | +public class MainClass3 { |
| 7 | + |
| 8 | + static boolean searchInAMatrix(int a[][], int key) { |
| 9 | + int row = 0; |
| 10 | + int col = a.length-1; |
| 11 | + |
| 12 | + while(row < a.length && col >= 0) { |
| 13 | + if(a[row][col] == key) { |
| 14 | + return true; |
| 15 | + } else if(key > a[row][col]) { |
| 16 | + row++; |
| 17 | + } else { |
| 18 | + col--; |
| 19 | + } |
| 20 | + } |
| 21 | + return false; |
| 22 | + } |
| 23 | + |
| 24 | + static void rotateMatrix(int a[][]) { |
| 25 | + int n = a.length; |
| 26 | + transposeOfAMatrix(a); |
| 27 | + |
| 28 | + for(int i = 0; i<n; i++) { |
| 29 | + for(int j = 0; j<n/2; j++) { |
| 30 | + int swap = a[i][j]; |
| 31 | + a[i][j] = a[i][n-j-1]; |
| 32 | + a[i][n-j-1] = swap; |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + |
| 38 | + static void printMatrix(int a[][]) { |
| 39 | + int n = a.length; |
| 40 | + for(int i = 0; i<n; i++) { |
| 41 | + for(int j = 0; j<n; j++) { |
| 42 | + System.out.print(a[i][j] +" "); |
| 43 | + } |
| 44 | + System.out.println(); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + static void transposeOfAMatrix(int a[][]) { |
| 49 | + int n = a.length; |
| 50 | + |
| 51 | + for(int i = 0; i<n; i++) { |
| 52 | + for(int j = i; j<n; j++) { |
| 53 | + int swap = a[i][j]; |
| 54 | + a[i][j] = a[j][i]; |
| 55 | + a[j][i] = swap; |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | + static boolean subArrayWithZeroSum(int a[]) { |
| 63 | + |
| 64 | + int n = a.length; |
| 65 | +// int prefixSum[] = new int[n]; |
| 66 | +// |
| 67 | +// prefixSum[0] = a[0]; |
| 68 | + |
| 69 | +// a = {2, 3, 1, -4, 4, -2}; |
| 70 | +// sum = 2 |
| 71 | +// |
| 72 | +// set = {2, 5, 6} |
| 73 | + |
| 74 | + |
| 75 | + Set<Integer> set = new HashSet<>(); |
| 76 | + int sum = 0; |
| 77 | + for(int i = 0; i<n; i++) { |
| 78 | + sum += a[i]; |
| 79 | + if(set.contains(sum)) { |
| 80 | + return true; |
| 81 | + } |
| 82 | + set.add(sum); |
| 83 | + } |
| 84 | + return false; |
| 85 | + } |
| 86 | + |
| 87 | + public static void main(String[] args) { |
| 88 | +// int a[] = {2, 3, 1, -4, 4, -2}; |
| 89 | +// |
| 90 | +// System.out.println(subArrayWithZeroSum(a)); |
| 91 | + |
| 92 | +// int a[][] = { |
| 93 | +// {1, 2, 3}, |
| 94 | +// {4, 5, 6}, |
| 95 | +// {7, 8, 9} |
| 96 | +// }; |
| 97 | +// |
| 98 | +// printMatrix(a); |
| 99 | +// |
| 100 | +//// transposeOfAMatrix(a); |
| 101 | +// |
| 102 | +// rotateMatrix(a); |
| 103 | +// |
| 104 | +// printMatrix(a); |
| 105 | + |
| 106 | + |
| 107 | + int a[][] = { |
| 108 | + {1, 4, 5, 7}, |
| 109 | + {2, 5, 6, 9}, |
| 110 | + {6, 10, 11, 13}, |
| 111 | + {8, 12, 15, 18} |
| 112 | + }; |
| 113 | + |
| 114 | + int key = 14; |
| 115 | + |
| 116 | + System.out.println(searchInAMatrix(a, key)); |
| 117 | + |
| 118 | + } |
| 119 | + |
| 120 | +} |
0 commit comments