TwoSum之Java实现

发布时间:2020-06-29 10:32:44 作者:xiezh10
来源:网络 阅读:187

一、题目

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].

二、题目理解

给定一个整型数组以及一个目标值,求数组中两个相加等于目标值的元素的索引。此题假设给定的数组中一定有两个元素相加等于目标值。

三、实现代码

1、第一种实现方式
使用暴力搜索的方式,用双层for循环遍历数组,拿数组的每一个元素与其他元素相加之后与目标值进行对比,找出符合要求的两个元素。
实现代码如下:

public int[] twoSum01(int[] nums, int target) {
    int[] result = new int[2];
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] == target) {
                result[0] = i;
                result[1] = j;
                break;
            }
        }
    }
    return result;
}

2、第二种实现方式
第一种实现方式在最坏的情况下的时间复杂度为O(n²),执行时间较长,不是一种比较好的实现方式,下面是第二种实现方法。
定义一个Map,遍历数组,每次都用目标值减去数组当前值得到差值temp,并判断temp是否存在于Map中,如不存在,则将数组当前值和索引存入Map中;如存在,则取出temp对应的索引值。
实现代码如下:

public int[] twoSum02(int[] nums, int target) {
    HashMap<Integer, Integer> tempMap = new HashMap<Integer, Integer>();
    int[] resultArr = new int[2];
    for(int i = 0; i < nums.length; i++) {
        // 用target减去数组当前值
        int temp = target - nums[i];
        // 判断HashMap中是否包含temp
        if(tempMap.get(temp) != null) {
            resultArr[0] = tempMap.get(temp);
            resultArr[1] = i;
            break;
        } else {
            tempMap.put(nums[i], i);        // 如不包含,就将当前值存入Map中
        }
    }
    return resultArr;
}
推荐阅读:
  1. java实现抽奖系统
  2. Valid Parentheses之Java实现

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

leetcode java 算法

上一篇:好程序员云计算学习路线分享软件包管理

下一篇:java判断字符串是数字的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》