算法练习专题——LeetCode系列之 Two Sum

在这个系列中给大家分享一些平常见到的算法题,以及自己的答案。

Question:

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:

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

    Because nums[0] + nums[1] = 2 + 7 = 9,

    return [0, 1].

Answer Template:

class Solution {
    public int[] twoSum(int[] nums, int target) {
      //your solution here
    }
}

Solution 1:

   public int[] twoSum(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};
                }
          }
        }
        throw new IllegalArgumentException("给定数组中没有满足条件的两个数");
    }

这种方法比较简单容易被想到,两层for循环遍历,时间复杂度是O(n2)

Solution 2:

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

        }
        throw new IllegalArgumentException("给定数组中没有满足条件的两个数");
    }

第二种解决方案使用了HashMap数据结构,只需要遍历一次,时间复杂度为O(n)

博主进行取10000个整数的数组{1,2,3, … , 10000} target = 19999做测试,第一种方法需要22ms,第二种方法只需要5ms。

以下是我的测试用例代码:

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] input = new int[10000];
        for(int i=1; i<=10000; i++) {
            input[i-1] = i;
        }
        new Thread(()->{
            long time =ExecutionTimeAnalyzer.getExecutionTime(() -> {
                System.out.println(Arrays.toString(twoSum(input, 19999)));
            });
            System.out.println(time+"ms");
        }).start(); 
        new Thread(()->{
            long time =ExecutionTimeAnalyzer.getExecutionTime(() -> {
                System.out.println(Arrays.toString(twoSum2(input, 19999)));
            });
            System.out.println(time+"ms");
        }).start();  

    }
public class ExecutionTimeAnalyzer {
    public static long getExecutionTime(CodeExecutor ce) {
        long startTime = System.currentTimeMillis();
        ce.execute();
        long endTime = System.currentTimeMillis();
        return (endTime-startTime);
    }
}
@FunctionalInterface
public interface CodeExecutor{
    void execute();
}

运行结果为:

    [9998, 9999]
    5ms
    [9998, 9999]
    22ms

本节博客的源码全部放在这里,欢迎大家下载,下载后记得修改源码中的package名字哦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值