LoginSignup
0
0

More than 1 year has passed since last update.

74 解答

Posted at

この問題はbinary searchの使用を目的としている。

参考

Nick White

n^2


public boolean searchMatrix(int[][] matrix, int target) {
		int m = matrix.length;
		int n = matrix[0].length;
		
		
		for(int i = 0; i < m; i++) {
			for(int j = 0; j < n; j++) {
				if(matrix[i][j] == target) {
					return true;
				} 
			}
			
		}
		return false;
	}

logn

public boolean searchMatrix(int[][] matrix, int target) {

		int rows = matrix.length;
		int columns = matrix[0].length;

		int left = 0;
		int right = (rows * columns) - 1;

		if (rows == 0)
			return false;

		while (left <= right) {
			int midpoint = left + ((right - left) / 2);
			int midpoint_element = matrix[midpoint / columns][midpoint%columns];
			if (midpoint_element == target) {
				return true;
			} else if (midpoint_element > target) {
				right = midpoint - 1;
			} else if (midpoint_element < target) {
				left = midpoint + 1;
			}
		}
		return false;
	}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0