LeetCode TwoSum解决方案不起作用
LeetCode TwoSum solution not working
#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
是一个关键字,用于为变量指定true
或false
。你必须使用另一个变量。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- C++Matching Brackets 2解决方案不起作用
- 为什么这段代码不起作用,我该如何解决?
- N-queen问题:无法弄清楚为什么我的解决方案不起作用
- EOF有更安全的替代方案吗?它在我的情况下不起作用
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- 在qt QFileDialog中设置后缀在linux中不起作用,如何解决?
- C++:传递临时值不起作用,如何解决?
- 为什么针对给定挑战的此解决方案不起作用?
- 解决方案在两个日期之间的天数内不起作用
- VS为我提供了对构造函数的另一个解决方案,但我想知道为什么我的工作不起作用
- C++迭代时删除列表成员:标准解决方案不起作用
- LeetCode TwoSum解决方案不起作用
- Strchr不起作用,或者我需要一个替代方案来检查给定字符串中的任何字符是否是另一个字符串的一部分
- C# COM-Interop dll for C++ COM dll 在 2 个解决方案之间不起作用
- RUSAGE_THREAD不起作用,正在寻找解决方案/替代方案
- Qt4,QPainterPath的直接分配不起作用(未解决的外部)