[Java算法]2、求和爲給定值的兩個數

題目描述和相關背景可以看這裏 :https://blog.csdn.net/hackbuteer1/article/details/6699642

public class Algorithm{

  // Time: O(n^2), Space: O(1)
  public int[] getTwoNumSumToGivenValueBruteForce(int[] nums, int target) {
    for (int i = 0; i < nums.length; ++i) {
      for (int j = i + 1; j < nums.length; ++j) {
        if (nums[i] + nums[j] == target)
          return new int[]{i, j};
      }
    }
    return new int[]{-1, -1};
  }

  // Time: O(n), Space: O(n)
  public int[] getTwoNumSumToGivenValueHashMap(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; ++i) {
      int numNeeded = target - nums[i];
      if (map.containsKey(numNeeded)) {
        return new int[]{map.get(numNeeded), i};
      }
      map.put(nums[i], i);
    }
    return new int[]{-1, -1};
  }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章