国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Java [leetcode 1] Two Sum

2019-11-14 23:56:32
字體:
來源:轉載
供稿:網友
java [leetcode 1] Two Sum

小二終于開通博客了,真是高興。最近在看Java,所以就拿leetcode練練手了。以后我會將自己解體過程中的思路寫下來,分享給大家,其中有我自己原創的部分,也有參考別人的代碼加入自己理解的部分,希望大家看了多提意見,一塊加油。

問題描述:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2

解體思路:

設立一個HashMap,其中鍵值key為數組中數值,對應值value則為該數組下標值。

從數組最開始往后遍歷,每次求出該值對應target-numbers[i]的值在HashMap中是否存在。如果該值已經存在,那么則找到兩個值的和為target值,返回即可;如果該值不存在,則把(numbers[i], i)放入HashMap中。

整個算法的時間復雜度為O(n)。

代碼如下:

import java.util.*;public class Solution {    public int[] twoSum(int[] numbers, int target) {                Map<Integer, Integer> map = new HashMap<Integer, Integer>(numbers.length * 2);        int[] results = new int[2];                for(int i = 0; i < numbers.length; i++){            Integer temp1 = map.get(target - numbers[i]);            if(temp1 == null){                map.put(numbers[i], i);            }            else{                results[0] = i + 1;                results[1] = temp1 + 1;                if(results[0] > results[1]){                    int temp2 = results[0];                    results[0] = results[1];                    results[1] = temp2;                }                return results;            }        }                return null;            }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 民丰县| 来凤县| 丰台区| 博客| 和政县| 彭州市| 平安县| 横峰县| 二手房| 含山县| 宁陵县| 保山市| 沈阳市| 建瓯市| 贵南县| 绍兴市| 丰顺县| 来凤县| 荔浦县| 荣成市| 永川市| 县级市| 刚察县| 敖汉旗| 石阡县| 大新县| 巴马| 西宁市| 铜鼓县| 兴和县| 乌兰浩特市| 炎陵县| 和静县| 乌兰县| 长宁县| 丹巴县| 永新县| 新津县| 保亭| 茂名市| 辉县市|