LC-1

Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

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

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

题解

  • 双 for 循环
  • for 循环 + HashMap,利用 containsKey 来处理 target - x 带来的一次 for 循环

Java实现,LC里面暴力双 for 执行用时更短。

package LC.hash;

import java.util.HashMap;

public class LC1 {
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        int[] res = twoSum(nums, target);
        for (int item :
                res) {
            System.out.println(item);
        }
    }

    public static int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> integerHashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (integerHashMap.containsKey(target - nums[i])) {
                return new int[]{integerHashMap.get(target - nums[i]), i};
            }
            integerHashMap.put(nums[i], i);
        }
        return new int[0];
    }
}

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        for(int i = 0; i < nums.length; i++){
            for(int j = nums.length - 1; j > i; j--){
                if(nums[i] + nums[j] == target){
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return result;
    }
}

Python实现

from typing import List


class Solution: 
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashtable = dict()
        for i, num in enumerate(nums):
            if target - num in hashtable:
                return [hashtable[target - num], i]
            hashtable[nums[i]] = i
        return []


test_nums = [2, 7, 11, 15]
teat_target = 9
res = Solution()
print(res.twoSum(test_nums, teat_target))


# class C(object):
#     @staticmethod
#     def f():
#         print('runoob');
# 
# 
# C.f();  # 静态方法无需实例化
# cobj = C()
# cobj.f()  # 也可以实例化后调用
posted @ 2022-03-21 16:33  Ricardo_ML  阅读(116)  评论(0编辑  收藏  举报