【问题标题】:LeetCode TwoSum solution not workingLeetCode TwoSum 解决方案不起作用
【发布时间】:2015-06-19 17:21:11
【问题描述】:
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
int bins(int* p,int lo,int hi,int t)
{//BinarySearch
    int mid=0;
    int c=0;
    if(lo<hi)
    {
        mid=(lo+hi)/2;
        if(p[mid]==t) c=1;
        else if(t>p[mid]) 
            bins(p,mid+1,hi,t);
        else if(t<p[mid]) 
            bins(p,0,mid,t);
    }
     return c;
}

int main()
{
    clrscr();
    int target;
    int k;
    int count=0;
    cout<<"Enter the number of elements:";
    cin>>k;
    int* numbers=new int(k);
    cout<<"Enter the target element"<<endl;
    cin>>target;
    cout<<"Enter the elements:"<<endl;
    for(int i=0;i<k;i++)
       cin>>numbers[i];
    int* nu=new int(k);
    memset(nu,0,sizeof(int));
    /*for(i=0;i<k;i++){
    cout<<numbers[i]<<endl;
    }*/
    for(i=0;i<k;i++)
    {
        int bool=bins(nu,0,k,numbers[i]);
        //printf("%d\n",bool);
        if(bool)
        {
             count++;
        }
        else
        {
            int tg=target-numbers[i];
            cout<<"targetval:"<<tg<<endl;
            nu[i]=tg;
        }
        //bool?count++:(nu[i]=target-numbers[i]);
    }
    cout<<"Count is:"<<count<<endl;
    getch();
    return 0;
}

这是我在 leetcode 中为 TwoSum 问题编写的代码,而不是使用时间复杂度为 O(n) 的 HashMap,我使用了复杂度为 O(logn) 的二进制搜索 我面临的问题是我给数组 numbers[i] 的输入只需要 3 个值,然后即使在从控制台分配正确的输入之后它也会存储垃圾值 该程序已在系统上的Turbocompiler上编译成功

【问题讨论】:

  • 您的复杂性从何而来?哈希表查找平均是恒定的(在最坏的情况下是线性的),二分查找是对数的。

标签: c++ arrays search initialization binary-search


【解决方案1】:
int* numbers=new int[k];////allocates an array of k adjacent integers. (undefined values)

您正在分配一个数组。检查符号。

您还使用关键字作为变量。(bool)。

你做了什么?

int *numbers=new int(k);////allocates an integer, set to k. (same syntax as constructors)

【讨论】:

    【解决方案2】:

    Leetcode 没有给出确切的代码。它将有语法错误或编译错误。您必须修复它们才能使其正常工作。在这种情况下,以下是问题,

    int* numbers=new int[k]; //not int* numbers=new int(k);
    

    另一件事是bool 是一个关键字,用于为变量提供truefalse。您必须使用另一个变量。

    【讨论】:

      猜你喜欢
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多