[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};
  }

}

猜你喜欢

转载自blog.csdn.net/qq_39400208/article/details/83341077
今日推荐