LeetCode刷題0001_two-sum

題目要求

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

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

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
複製代碼

方法一:暴力破解法

暴力法很簡單,遍歷每一個元素 xx,並查找是否存在一個值與 target−x 相等的目標元素。bash

複雜度分析

  • 時間複雜度:O(n^2)
  • 空間複雜度:O(1)

代碼實現java

class Solution {
  public int[] twoSum(int[] nums, int target) {
    for(int i = 0 ; i < nums.length; i ++){
      for(int j = 0 ; j < nums.length ; j ++){
        if(nums[i] + nums[j] == target){
          int[] res = {i, j};
          return res;
        }
      }
    }
    throw new IllegalStateException("the input has no solution");
  }
}
複製代碼

方法二:哈希表

使用HashMap,基本思路是:用數組的值做爲key,index做爲value。對數組進行迭代的時候,將元素插入到hashMap中的,這時咱們回過頭來檢查表中是否已經存在當前元素所對應的目標元素。若是它存在,那咱們已經找到了對應解,並當即將其返回。ui

複雜度分析

  • 時間複雜度:O(n)
  • 空間複雜度:O(n), 所需的額外空間取決於哈希表中存儲的元素數量,該表最多須要存儲 nn 個元素。

java代碼實現

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int temp =target-nums[i];
            if(map.containsKey(temp)){  // 返回布爾
                return new int []{map.get(temp),i};
            }
            map.put(nums[i],i);   // key value
        }
        throw new IllegalStateException("the input has no solution");
    }
}
複製代碼
相關文章
相關標籤/搜索