遍历有序数组一次以检查是否有任何两个元素满足(一起)条件

时间:2017-12-19 13:36:48

标签: c#

如果任何两个元素具有给定值的 sum ,并且仅遍历数组,则如何检查具有有序的int元素数组:int[] ? 我通过遍历数组两次解决了这个问题。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

尝试同时扫描两个结尾(leftright):在提前一步移动left后,调整right边框;在这种情况下,您只需读取一次数组的项目。像这样:

private static Tuple<int, int> FindPair(int[] data, int sum) {
  int left = -1;
  int right = data.Length;

  while (left < right) {
    left += 1;

    if (left >= right)
      break;

    int leftValue = data[left];

    // Having new left border, we have to adjust right border
    for (int r = right - 1; r > left; --r) {
      int rightValue = data[r];

      if (rightValue + leftValue == sum)
        return new Tuple<int, int>(left, r);
      else if (rightValue + leftValue > sum)
        right -= 1;
    }
  }

  return new Tuple<int, int>(-1, -1);
}

试验:

int[] data = new int[] { 2, 3, 4, 5, 7, 10, 12};

var report = string.Join(Environment.NewLine, Enumerable
  .Range(4, 20)
  .Select(sum => $"{sum,2}: {FindPair(data, sum)}"));

Console.WriteLine(report);

结果:

 4: (-1, -1)
 5: (0, 1)
 6: (0, 2)
 7: (0, 3)
 8: (1, 3)
 9: (0, 4)
10: (1, 4)
11: (2, 4)
12: (0, 5)
13: (1, 5)
14: (0, 6)
15: (1, 6)
16: (2, 6)
17: (3, 6)
18: (-1, -1)
19: (4, 6)
20: (-1, -1)
21: (-1, -1)
22: (5, 6)
23: (-1, -1)