【leetcode】-1. Two Sum 两数和

Two Sum

  • 题目
  • 哈希表

题目

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

哈希表

一般如果数组有序的话,可以使用前后指针方法得到两数和与target比较。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int left = 0;
        int right = nums.length-1;
        while(lefttarget)
                right --;
        }
        return new int[]{-1,-1};
  

这题没有说明是有序数组,所以可以是无序的,如果想用前后指针的方法的话可以先进行排序。也可以使用哈希表的方式将元素映射到索引,然后查找当前元素的余数是否在哈希表中。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n=nums.length;
        Map index = new HashMap<>();
        
        for(int i=0;i

你可能感兴趣的:(LeetCode)