LeetCode--数组Input array is sorted

给定一个升序正整数数组和一个目标值,找到两个数字,使它们相加到一个特定的目标号码。函数twoSum应该返回两个数字的索引,使它们相加到目标,其中index1必须小于index2。请注意,您返回的答案(index1和index2)都不是基于零的。你可以假设每个输入都只有一个解决方案。
Example
输入:numbers = {2,7,11,15},target = 9
输出:index1 = 1,index2 = 2

- (NSDictionary *)getArray:(NSArray *)array target:(NSInteger)target {
    
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    
    NSInteger start = 0;

    NSInteger end = array.count - 1;

    while (start < end) {

        NSInteger sum = [array[start] integerValue] + [array[end] integerValue];
        
        if (target == sum) {
            
            NSLog(@"index1 = %ld,index2 = %ld",start+1,end + 1);
            
            [result setValue:[NSString stringWithFormat:@"%ld",start + 1] forKey:@"index1"];
            
            [result setValue:[NSString stringWithFormat:@"%ld",end + 1] forKey:@"index2"];
            break;
        }else if (target > sum) {
            
            start ++;
        }else {
            
            end --;
        }
       
    }
    return result;
}

你可能感兴趣的:(LeetCode--数组Input array is sorted)