Given a m * n
matrix of distinct numbers, return all lucky numbers in the matrix in any order.
A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.
Example 1:
Input: matrix ={{3,7,8},{9,11,13},{15,16,17}}
Output: lucky={15}
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class LuckyNumbersInMatrix {public static void main(String[] args) {int matrix[][] = { { 3, 7, 8 }, { 9, 11, 13 }, { 15, 16, 17 } };List<Integer> lucky = luckyNumbers(matrix);System.out.println(Arrays.asList(lucky));}// method to find the lucku numbers// in the given matrixstatic List<Integer> luckyNumbers(int[][] matrix) {int n = matrix.length;int m = matrix[0].length;int row[] = new int[n];for (int i = 0; i < n; i++)row[i] = Integer.MAX_VALUE;int col[] = new int[m];for (int i = 0; i < m; i++)col[i] = Integer.MIN_VALUE;for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {if (row[i] > matrix[i][j])row[i] = matrix[i][j];}}for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (col[i] < matrix[j][i])col[i] = matrix[j][i];}}List<Integer> res = new ArrayList<Integer>();for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {if (matrix[i][j] == row[i] && matrix[i][j] == col[j]) {res.add(matrix[i][j]);}}}return res;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the lucku numbers//in the given matrixvector<int> luckyNumbers (vector<vector<int>>& matrix){int n=matrix.size();int m=matrix[0].size();int row[n];for(int i=0;i<n;i++)row[i]=INT_MAX;int col[m];for(int i=0;i<m;i++)col[i]=INT_MIN;for(int i=0;i<matrix.size();i++){for(int j=0;j<matrix[0].size();j++){if(row[i]>matrix[i][j])row[i]=matrix[i][j];}}for(int i=0;i<matrix[0].size();i++){for(int j=0;j<matrix.size();j++){if(col[i]<matrix[j][i])col[i]=matrix[j][i];}}vector<int> res;for(int i=0;i<n;i++){for(int j=0;j<m;j++){if(matrix[i][j]==row[i]&&matrix[i][j]==col[j]){res.push_back(matrix[i][j]);}}}return res;}int main(){vector<vector<int>> matrix ={{3,7,8},{9,11,13},{15,16,17}};vector<int> lucky=luckyNumbers(matrix);for(int i=0;i<lucky.size();i++)cout<<lucky[i]<<" ";return 0;}
No comments:
Post a Comment