我是靠谱客的博主 愉快小霸王,最近开发中收集的这篇文章主要介绍1.两数之和,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

题目链接

力扣https://leetcode.cn/problems/two-sum/

题目描述

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值target
的那两个整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

 

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]

题解一  暴力破解

思路:

使用两个for循环,时间复杂度o(n2)'

class Solution {
        public int[] twoSum(int[] nums, int target) {
            // 暴力破解法
            return baoLi(nums, target);
        }

        public int[] baoLi(int[] nums, int target) {
            int len = nums.length;
            int[] arr = new int[2];
            for (int i = 0; i < len - 1; i++) {
                int value = target - nums[i];
                // 当前j从i的下一个数值开始,直至最后一个数完成一词遍历
                for (int j = i + 1; j < len; j++) {
                    if (nums[j] == value) {
                        arr[0] = i;
                        arr[1] = j;
                        return arr;
                    }
                }
            }
            return null;
        }
}

题解二 hash

思路:

使用暴力破解的时间复杂度为O(n2),而使用hash解法的时间复杂度是o(n),如下。遍历数组,假设当前元素是i,则val = target-i为我们要找的第二个加数的值。我们使用一个map<Integer ,Integer >来存储数组里的值和索引,其中key存值,value存当前值对应的索引。如果val在map中不存在,则将当前i对应的值和i存入map,如果存在直接返回对应值和索引。

 class Solution {
        public int[] twoSum(int[] nums, int target) {
            // 暴力破解法
            // return baoLi(nums, target);

            return hashHandle(nums, target);
        }

        public int[] hashHandle(int[] nums, int target) {
            int len = nums.length;
            // key为数组中的值,value为值对应调得索引
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < len; i++) {
                if (map.containsKey(target - nums[i])) {
                    return new int[] {map.get(target - nums[i]), i};
                }
                map.put(nums[i], i);
            }
            return null;
        }
    }

最后

以上就是愉快小霸王为你收集整理的1.两数之和的全部内容,希望文章能够帮你解决1.两数之和所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部