Two Sum算法

来源:互联网 发布:局域网设置域名 编辑:程序博客网 时间:2024/06/01 22:09


①算法描述:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

解决方法:
  
一:使用java for循环,暴力搜索方式
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[j] == target - nums[i]) {                return new int[] { i, j };            }        }    }    throw new IllegalArgumentException("No two sum solution");}

二:使用Hashmap,将时间复杂度减小到O(n)

public class Solution{    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 j=0;j<nums.length;j++)        {            int complements=target-nums[j];            if(map.containsKey(complements)&&map.get(complements)!=j)                {                    return new int [] {j,map.get(complements)};                                }         }        throw new IllegalArgumentException("No two sum solution");}    }


原创粉丝点击