zoukankan      html  css  js  c++  java
  • 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!
    ";
                }
                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
    ", dupli);
        }
        else{
            printf("No Duplicate
    ");
        }
        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;
    }
    
    
    
    
  • 相关阅读:
    构造方法,析构函数
    Redis Sentinel实现的机制与原理详解
    关于PageRank的总结
    再次建立wordpress
    图的研究杂记
    并行的论文
    还是bib问题
    如何解决bib的一些问题
    忙中记录
    近期一些学术相关记录
  • 原文地址:https://www.cnblogs.com/DianeSoHungry/p/11270000.html
Copyright © 2011-2022 走看看