[关闭]
@w1024020103 2017-01-04T00:11:03.000000Z 字数 1709 阅读 608

Interview Questions

Algorithm 算法 Coursera Java Interview

Question 1

2-SUM in quadratic time. Design an algorithm for the 2-SUM problem that takes time proportional to in the worst case. You may assume that you can sort the integers in time proportional to or better.

brute force

If we use brute force to solve Two Sum, it will cost us to find the answer.

  1. import java.util.ArrayList;
  2. import java.util.Scanner;
  3. import java.io.*;
  4. public class TwoSumBrute{
  5. public static void main(String[] args) throws IOException {
  6. Scanner scan = new Scanner(new File("Data.txt"));
  7. ArrayList<Integer> data = new ArrayList<Integer>();
  8. while (scan.hasNextInt()) {
  9. data.add(scan.nextInt());
  10. }
  11. int x = 20;
  12. int N = data.size();
  13. for (int i = 0; i < N; i++){
  14. for (int j = i + 1; j < N; j++){
  15. if (data.get(i) + data.get(j) == x) {
  16. System.out.println("i = " + data.get(i)+" j = " + data.get(j));
  17. }
  18. }
  19. }
  20. }
  21. }

Sorting

We can sort the array to make it easier. For Two Sum, if the array is sorted, we can use two pointers pointing to the head and the end. If the sum is smaller than target, we can move the first pointer right. If the sum is larger than target, we can move the second pointer left. We will continue doing this until we find the target or the position of first pointer is larger than the second pointer. We can also use this in 3 Sum. We can use each entry as a candidate. For example, we now searching 2 other elements in the array that makes their sum equals to target – num[i]. We can just check the entries from i + 1 to num.length – 1, with the method mentioned above.
The complexity of this method is better than brute force method. Sorting the array costs . So, for Two Sum, it costs ..

  1. import java.util.Arrays;
  2. public class TwoSumSort{
  3. }

HashMap

We can use HashMap to improve this algorithm. For example, it can improve Two Sum from to . That is, saving every number in the HashMap as well as its position. And then we can go through the array and check for the existence number target – i in . So we only need .

  1. public class TwoSumHash {
  2. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注