问题
Suppose I have a sorted array of integers int[], and I want to search the closest smaller value to some input number.
for example if the array contains 1
, 23
, 57
, 59
, 120
and the input is 109
, the output should be 59
.
I have tried this but it is not working out as needed.
NSTimeInterval currentTime = self.player.currentTime;
NSInteger playerTime=currentTime;
NSUInteger index = [_timesArray indexOfObject:@(playerTime)
inSortedRange:NSMakeRange(0, _timesArray.count-1)
options:NSBinarySearchingFirstEqual | NSBinarySearchingInsertionIndex
usingComparator:^(id a, id b) {
return [a compare:b];
}];
回答1:
Your code does work as expected with the example data you gave:
NSArray *_timesArray = @[@1, @23, @57, @59, @120];
NSTimeInterval currentTime = 109;
NSInteger playerTime=currentTime;
NSUInteger index = [_timesArray indexOfObject:@(playerTime)
inSortedRange:NSMakeRange(0, _timesArray.count-1)
options:NSBinarySearchingFirstEqual | NSBinarySearchingInsertionIndex
usingComparator:^(id a, id b) {
return [a compare:b];
}];
NSLog(@"Index: %lu", (unsigned long)index);
Output:
Index: 4
Check your inputs. Likely they are not what you think they are.
回答2:
As I said before: "you have sorted array and what you need is to step downward from biggest number to smallest... algorithm is simple here!"
NSNumber* givenNumber = @(105);
for (NSNumber* item in [@[@(1), @(23), @(57), @(59), @(120)] reverseObjectEnumerator]){
// go downward
if (item.integerValue < givenNumber.integerValue)
{
NSLog(@"%@ < %@",item,givenNumber);
// save this number somewhere
break;
}
}
回答3:
It can be solved by binary_search_like algorithm which runs in O(lg n) , but I don't know objective-c so I'll give code in c++.
I assume the given element is not in the array.
int binary_search_like(int s[], int key, int low, int high)
{
int middle;
if (low > high) return (s[high]);
middle = (low + high) / 2;
if (s[middle] > key)
return(binary_search_like(s, key, low, middle - 1));
else
return(binary_search_like(s, key, middle + 1, high));
}
int Search(int s[], int key, int size){
if (key > s[size - 1]) return s[size - 1];
// Check if key < smallest element , give error !
return binary_search_like(s, key, 0, size);
}
来源:https://stackoverflow.com/questions/25238072/find-the-largest-number-from-nsarray-that-is-smaller-than-the-given-number