欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 数组操作算法

程序员文章站 2022-07-10 09:18:17
1. Two Sum一、题目Problem Description: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 elem...

1. Two Sum

一、题目

Problem Description:
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]

Constraints:
2 <= nums.length <= 103
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

二、题解

  • 在给定数组中找到两数之和为目标值的唯一解,结果返回2个数字的下标。

2.1 Approach #1 : Brute Force

暴力破解方法想法很简单,也很容易实现。两个for循环遍历所有可能结果的数字对,找到两数之和等于目标值,返回两数所对应的索引。

此解法易于理解,但时间复杂度较高。

Time complexity : O ( 2 n ) O(2^n) O(2n)
Space complexity : O ( 1 ) O(1) O(1)

//Brute Force
//Time complexity : O(n^2); Space complexity : O(1)
class Solution {
    public static int[] twoSum(int[] nums, int target) {
		int[] res = new int[2];
        for(int i = 0; i < nums.length-1; i++){
            for(int j = i+1; j < nums.length; j++){
                if(nums[i] + nums[j] == target){
                	res[0] = i;
                	res[1] = j;
					return res;
                }
            }
        }
        return res;
    }
}

2.2 Approach #2 : Hash Table

此题最优解法的时间复杂度为 O ( n ) O(n) O(n)
顺序扫描数组,对每一个元素,在map中找到和为目标值的另一个数。如果找到了,直接返回2个数字的下标即可;如果没找到将这个数以<key = nums[i], value = i>键值对的形式存入map中,等到扫描到另一个数,再取出索引(value值)返回即可

键值对形式:<key = 数组元素值, value = 数组元素值对应的索引>,即<key = nums[i], value = i>

注:理想情况下,HashMap的增、删、改、查等操作的时间复杂度都为 O ( 1 ) O(1) O(1)

Time complexity : O ( n ) O(n) O(n)
Space complexity : O ( n ) O(n) O(n)

//Hash Table
//Time complexity : O(n); Space complexity : O(n)
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int[] res = new int[2];
        for(int i = 0; i < nums.length; i++){
            int temp = target - nums[i];
            if(map.containsKey(temp)){
                res[0] = map.get(temp);
                res[1] = i;
                return res;
            }else{
                map.put(nums[i], i);
            }
        }
        return res;
    }
}

本文地址:https://blog.csdn.net/KKKKKKOBE_24/article/details/110290294