Diane洗刷刷剑指Offer

保证原创,欢迎交流
如有雷同,纯属巧合

数组

P39

//
//  Created by Diane on 7/30/19.
//  Copyright © 2019 Diane. All rights reserved.
//

//  Given an array of length n, where each element falls in [0, n-1], You are asked to find a duplicate from this array
//  Time Complexity: O(N)
//  Space Complexity: O(1)

#include<iostream>
#include<assert.h>
using namespace std;
bool hasDupli(int *a, int n, int* dupli);

int main()
{
    //  take input
    int n;
    while(true){
        try{
            scanf("%d", &n);
            if(n<0){    //  Be aware of the situation when n < 0
                throw "Length of array can not be less than 0, try again!\n";
            }
            break;
        }
        catch(const char* e){
            cout << e;
        }
    }
    int a[n];
    for(int i = 0; i < n; i++)
    {
        scanf("%d", &a[i]);
    }
    //  Check and print output
    int dupli;
    if(hasDupli(a, n, &dupli)){
        printf("Duplicate %d Found\n", dupli);
    }
    else{
        printf("No Duplicate\n");
    }
    return 0;
    
}

bool hasDupli(int a[], int n, int* p){
    if(n<0){
        return false;
    }
    int i = 0;
    while(i < n){
        if(a[i] == i){
            i++;
            continue;
        }
        else{
            if(a[a[i]] == a[i]){
                *p = a[i];
                return true;
            }
            else{
                int tmp = a[a[i]];
                a[a[i]] = a[i];
                a[i] = tmp;
            }
        }
    }
    return false;
}

字符串


#include <iostream>
#include <cstdio>

using namespace std;
int main(){
    char str1[] = "hello, world";
    char str2[] = "hello, world";
    char* str3 = "hello, world";
    char* str4 = "hello, world";
    cout << "&str1 == &str2: " << (&str1 == &str2) << endl;
    cout << "str1 == str2: " << (str1 == str2) << endl;
    cout << "&str3 == &str4: " << (&str3 == &str4) << endl;
    cout << "str3 == str4: " << (str3 == str4) << endl;
    cout << "&str1: " << &str1  << endl;
    cout << "&str2: " << &str2  << endl;
    cout << "&str3: " << &str3  << endl;
    cout << "&str4: " << &str4  << endl;
}



posted @ 2019-07-30 14:50  DianeSoHungry  阅读(108)  评论(0编辑  收藏  举报