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]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]
解题:
  1. 暴力双循环法

    时间复杂度:O(n^2),双重循环外循环为n,内循环为n。

    	/**
    	 * 暴力双重循环方式
    	 */
    	public static int[] twoSum1(int[] nums, int target) {
    	    if (null == nums) {
    	        return null;
    	    }
    	    final int LENGTH = nums.length;
    	    for (int i = 0; i < LENGTH - 1; i++) {
    	        for (int j = i; j < LENGTH; j++) {
    	            if (target == nums[i] + nums[j]) {
    	                return new int[] {i, j};
    	            }
    	        }
    	    }
    	
    	    return new int[] {};
    	}
    
  2. 构建Hash结构存储数据

    时间复杂度:O(n),外循环为n,从 Hash 中读取数据为 O(1)。

       /**
        *  以空间换时间,将访问过的数据存储到 Hash 表中,再次读取即为非线性读取,效率高
        */
       public static int[] twoSum2(int[] nums, int target) {
           if (null == nums) {
               return null;
           }
           final int LENGTH = nums.length;
           // 初始化 hash 容器容量
           HashMap<Integer, Integer> numHashMap = new HashMap<>(LENGTH);
           Integer temp;
           for (int i = 0; i < LENGTH; i++) {
               int devideValue = target - nums[i];
               temp = numHashMap.get(devideValue);
               if (null != temp) {
                   return new int[] {temp, i};
               }
               numHashMap.put(nums[i], i);
           }
           return new int[]{};
       }
    
  3. 如果给出题目中数组值是 递增 的,则还可以使用双指针来优化

    输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。

        public static int[] twoSum3(int[] nums, int target) {
            if (null == nums) {
                return null;
            }
    
            final int LENGTH = nums.length;
            int head = 0, tail = LENGTH - 1;
            while (head < tail) {
                int temp = nums[head] + nums[tail];
                if (temp > target) {
                    tail--;
                } else if (temp < target) {
                    head++;
                } else {
                    return new int[] {head, tail};
                }
            }
    
            return new int[] {};
        }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值