如何找到一个好的解决方案或优化解决方案

时间:2019-03-31 21:55:45

标签: java data-structures

我接受了一家公司的采访,被要求为以下每​​个问题编写代码。我在不到15分钟的时间内完成了代码。几天后,我收到一条消息,说他们已决定与其他候选人继续。我想不出任何更好的解决方案来回答这些问题。如果您能帮助我更好地理解为什么我的解决方案不够好以及如何改进它,我将不胜感激。

Queston:假设我们有一个整数流(一个很大的列表)。类似于:1、2、7、3、9、4、1、2、5,...,-1。流中的最后一个元素始终为“ -1”。函数 int read()返回流中的下一个元素,没有其他方法可以读取该流。

  • 编写方法 int [] last5(),该方法从流中返回最后5个元素。
  • 编写方法 int [] last5unique(),该方法返回按流中最后出现的位置(位置)排序的后5个唯一元素。例如,流:1 2 3 2 4 5按出现次数排序的后5个是:1 3 2 45。请注意,后2的位置大于后3的位置。

然后我想到了

public int[] last5() {

  int[] toReturn = new int[5];

  int last = read(); 
  int counter = 0; 
  toReturn[counter] = last; 
  counter++; 

  while (last != -1) {
    last = read(); 
    toReturn[counter] = last; 
    counter++; 

    if (counter == 5) {
      counter = 0 
    }
  }
  return toReturn;
}


public int[] last5unique() {

  int[] toReturn = new int[5];
  Vector<Integer> tmp = new Vector<Integer>();

  int last = read(); 
  tmp.add(last); 

  while (last != -1) {
    last = read(); 
    if (!tmp.contains(last)) {
      tmp.add(last); 
    }
    else {
      for (int i=0; i<tmp.size(); i++) {
        if (tmp.get(i) == last) {
          tmp.remove(i); 
          break;
        }
      }
      tmp.add(last); 
    }
    if (tmp.size() == 5 && last != -1) {
      tmp.remove(0); 
    }
  }

  for (int i=0; i<tmp.size(); i++)
    toReturn[i] = tmp.get(i);

  return toReturn;
}

1 个答案:

答案 0 :(得分:0)

您的last5()函数是错误的,因为如果您在读取5个数字后有6个数字(或不是5的倍数的任何数量),则将从位置[0]的原因再次开始写入

if (counter == 5) {
  counter = 0 
}

,我认为这不是他们要求的功能。 如果流是 0、1、2、3、4、5、6、7,-1 ,则函数将返回 5、6、7、3、4 ,但我认为它应该返回 3、4、5、6、7

我对last5()的解决方案如下:

public int[] last5() {
        LinkedList<Integer> list = new LinkedList<>();
        int[] toReturn = new int[5];
        int quantity = 0;
        int last;

        last = read();
        while (last != -1) {
            list.add(last);

            if (quantity >= 5)
                list.pop();
            else
                quantity++;
            last = read();
        }

        for (int i = 0; i < quantity; i++) {
            toReturn[i] = list.get(i);
        }
        return toReturn;
    }
}

我使用LinkedList保留了只有5个元素(或更少)的队列数据结构。您也可以避免使用LinkedList,但是在读取5个元素之后,需要额外的while / for循环才能将所有元素移到先前的位置。 这样,您可以保留流中元素的原始位置。

相关问题