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;
}


转载于:https://www.cnblogs.com/DianeSoHungry/p/11270000.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值