小编Jos*_*hua的帖子

面试问题:包含相等数量的两个整数的最长前缀

我尝试在技术面试的在线评估中解决以下问题,但失败了。我已经思考这个问题有一段时间了,似乎找不到令我满意的答案:

您正在寻找数组 A 的最长前导片段(前缀),其中 X 和 Y 出现的次数相等,其中 X 和 Y 是整数。

例如,当 X=7 且 Y=42 时,A=[6, 42, 11, 7, 1, 42] 的最长前缀将为 4,因为 A[0]-A[4] 包含相同数量的X 和 Y。

另一个例子,X=6,Y=13。A=[13,13,1,6]。该函数应返回 -1,因为没有前缀。

X=100、Y=63 和 A=[100,63,1,6,2,13] 应返回 5。

我尝试用 C 语言回答:

int solution(int X, int Y, int A[], int N){
  int result=-1;
  int nX=0; //number of occurrences of X
  int nY=0; //number of occurrences of Y
  int i;
  for(i=0;i<N;i++){//loop through the input array
    if(A[i]==X)//occurrence of X
      nX += 1;

    /*
    EDGE CASE BELOW: …
Run Code Online (Sandbox Code Playgroud)

c algorithm

3
推荐指数
1
解决办法
1万
查看次数

在 Visual Studio 中检测到堆损坏,但程序在另一个 C 编译器中运行良好:为什么?

我尝试寻找这个问题,但找不到任何答案。我编写了一个程序,用链表实现堆栈及其操作。该程序在 C Web IDE 上编译并完美运行。

当我在 Visual Studio 中运行该程序时,它失败并给出以下错误:

调试错误!程序:C:\Users...我的文件路径检测到堆损坏:在 0x011058C8 处的正常块(#78)之后。CRT 检测到应用程序在堆缓冲区末尾后写入内存。

由于我的代码在其他地方运行良好,这一定是我使用 Visual Studio 的方式存在问题。有任何想法吗?我是 Visual Studio 的新手,恐怕这可能是愚蠢的事情,但我似乎无法弄清楚。

我在下面包含了我的代码,请注意,失败是由 Visual Studio 中的 pop() 函数引起的。

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

struct Node* top = NULL; //initialize head

void push(int x);
void push(int x) {
    struct Node* add = (struct Node*)malloc(sizeof(struct Node*));
    add->data = x;
    add->next = top; //make add point to what top (head) points to (old 1st)
    top = add; …
Run Code Online (Sandbox Code Playgroud)

c heap-corruption visual-studio-2019

1
推荐指数
1
解决办法
2093
查看次数