在一個二維數(shù)組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序础淤,輸入一個二維數(shù)組中的數(shù)字莹捡,判斷二維書中是否存在,存在返回true鬼吵,不存在返回false~
查詢:
class SearchDimension: NSObject {
func searchNumber(data:Array<AnyObject>,number:NSInteger)->Bool{
if data.count>0 && data[0].count>0 {
var row=0
let rows=data.count
let columns=data[0].count
var column=columns-1
while row<rows && column>=0 {
let rightValue=data[row][column] as! NSInteger
//存在
if rightValue==number {
print("current row:\(row)--current column:\(column)")
return true
} else if rightValue>number {//數(shù)值小于右上角的值,排除一列
column=column-1
} else {//數(shù)值大于右上角的值篮赢,排除一列
row=row+1
}
}
}
return false;
}
}
測試代碼:
var data=[[1,2,6,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
var search=SearchDimension()
var number=6
var isExist = search.searchNumber(data, number: number)
print("FlyElephant:data contains \(number) is \(isExist)")`