LeetCode TwoSum解决方案不起作用

LeetCode TwoSum solution not working

本文关键字:不起作用 解决方案 TwoSum LeetCode      更新时间:2023-10-16
#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("%dn",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,我使用了复杂度为0(logn)的二进制搜索我面临的问题是,我给数组编号[i]的输入只取3个值,从那时起,即使从控制台分配了正确的输入,它也会存储垃圾值该程序已在系统的Turbo编译器上成功编译

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)

Leetcode没有给出确切的代码。它将有语法错误或编译错误。你必须修复它们才能让它发挥作用。在这种情况下,以下是问题,

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

另一件事是,bool是一个关键字,用于为变量指定truefalse。你必须使用另一个变量。