剑指offer-数组中重复的数字

题目一:找出数组中重复的数字
在一个长度为n的数组里所有数字都在0~n-1的范围内,数组中某些数字是重复的,单不知道有几个重复数字,也不知道每个数字重复了几次,请找出数组中任意的数字,例如长度为7的数组{2,3,1,0,2,5,3},那么对应的重复数字2或者3

因为数字不重复而且在0~n-1内,所以解题精髓就是用数组把内容插入到数组坐标的相应位置,然后比对 如果发现该数字在数组坐标位置相同则代表有重复。

官方demo

//
//  main.cpp
//  数组中找重复
//
//  Created by 张传奇 on 2018/8/1.
//  Copyright © 2018年 张传奇. All rights reserved.
//

#include 

bool duplicate(int numbers[],int length,int * duplication) {
    
    if (numbers == nullptr || length <= 0) {
        return false;
    }
    
    for (int i=0 ; i length -1) {
            return false;
        }
    }
    
    for(int i=0; i

OC版本

//
//  main.m
//  数字中重复数字
//
//  Created by 张传奇 on 2018/7/31.
//  Copyright © 2018年 张传奇. All rights reserved.
//

#import 

BOOL duplicate(NSMutableArray * numbers,int * duplication) {
    
    if (numbers == nil || numbers.count <1) {
        return NO;
    }
    for (NSNumber * obj in numbers) {
        if (obj.intValue < 0 || obj.intValue > numbers.count-1) {
            return NO;
        }
    }
    
    for (int i=0; i

Tips:吐槽吐槽 oc写算法实在太操蛋了,手写感觉有点凉凉

题目二:不修改数组找出重复的数字
在一个长度为n+1的数组里的所有数字都在1~n的范围,所有数组中至少有一个数字是重复的。请找出数组中的任意一个重复的数字,但不能修改输入的数组。例如,如果输入长度为8的数组{2,3,5,4,3,2,6,7},那么对应的输出是重复的数字2或者3。

你可能感兴趣的:(剑指offer-数组中重复的数字)