Two Sum

ゝ一世哀愁。 2022-05-30 12:06 257阅读 0赞

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

  1. Given nums = [2, 7, 11, 15], target = 9,
  2. Because nums[0] + nums[1] = 2 + 7 = 9,
  3. return [0, 1].

此题可以用暴力求解,两个循环判断是否数组中存在两个数相加为目标值(不可自身与自身相加)

  1. public int[] twoSum(int nums[], int target) {
  2. int k = 0;
  3. for (int i=0; i<nums.length; i++) {
  4. for (int j=i+1; j<nums.length; j++) {
  5. if (nums[j] == (target - nums[i])) {
  6. return new int[] {i, j};
  7. }
  8. }
  9. }
  10. return null;
  11. }

我们可以看到这种求法时间复杂度为O(n^2) 空间复杂度为O(1)

现在我们打算用空间换时间,改用hashmap来求解

  1. public int[] twoSum(int nums[], int target) {
  2. HashMap<Integer, Integer> hm = new HashMap<>();
  3. for (int i=0; i<nums.length; i++) {
  4. hm.put(nums[i], i);
  5. }
  6. for (int i=0; i<nums.length; i++) {
  7. // cause the question needs us use different element
  8. if (hm.containsKey(target - nums[i]) && (i != hm.get(target - nums[i]))) {
  9. return new int[] {i, hm.get(target - nums[i]).intValue()};
  10. }
  11. }
  12. return null;
  13. }

这样时间和空间复杂度都成了O(n)

发表评论

表情:
评论列表 (有 0 条评论,257人围观)

还没有评论,来说两句吧...

相关阅读