1. Two Sum

    xiaoxiao2021-09-21  53

    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. Example:

    Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

    题目意思是给定一个数组以及目标值,找出数字中对应的两个元素的索引。 方法1: 我的方法—>暴力方法,循环比较所有两两元素和的比较。

    public class Solution { public int[] twoSum(int[] nums, int target) { int size=nums.length; int [] num=new int[2]; int sum; for(int i=0;i<size-1;i++) for(int j=i+1;j<size;j++) { if(nums[i]+nums[j]==target) { num[0]=i; num[1]=j; } } return num; } }

    时间复杂度O(n2),空间复杂度O(1)

    方法2: 哈希表法:

    public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement) && map.get(complement) != i) { return new int[] { i, map.get(complement) }; } } throw new IllegalArgumentException("No two sum solution"); }

    时间复杂度O(n)

    转载请注明原文地址: https://ju.6miu.com/read-677771.html

    最新回复(0)