标签:
题目描述:public class Solution { public bool SearchMatrix(int[,] matrix, int target) { var rowLen = matrix.GetLength(0); var colLen = matrix.GetLength(1); // first , locate the target in which row int? rowIndex = null; for(var i = 0;i < rowLen - 1; i++){ if(target >= matrix[i,0] && target < matrix[i+1,0]){ rowIndex = i; break; } } // try find in last row if(!rowIndex.HasValue){ rowIndex = rowLen - 1; } // try find the target in matrix[row,0...n] var colArr = new int[colLen]; for(var i = 0; i < colLen; i++ ){ colArr[i] = matrix[rowIndex.Value, i]; } var found = BSearch(colArr, target); return found.HasValue; } public int? BSearch(int[] arr, int n){ for(var i =0 ;i < arr.Length; i++){ var l = i; var r = arr.Length - 1; var m = arr.Length / 2; if(n == arr[l] || n == arr[r] || n == arr[m]){ return n; } if(n > arr[m]){ l = m; } else { r = m; } } return null; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/48650073