LeetCode 1、Two Sum

来源:互联网 发布:pptv网络电视怎么看直播 编辑:程序博客网 时间:2024/06/06 09:59

这里写图片描述

题目大意:给一个数组num和一个给定的数t,假设数组中两个数相加等于t,给出这两个数的下标【假设答案只有一组】
1)用java中的hashmap解决

package com;        import java.util.Arrays;        import java.util.HashMap;/** * Created by hms on 2016/12/22. */public class Solution {    public int[] twoSum(int[] nums, int target) {        int index[] = {0, 0};        HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();        int n = nums.length;        for(int i = 0; i < n; ++i){            if(hashMap.containsKey(nums[i])){                if(nums[i] == target - nums[i]){                    int k = hashMap.get(nums[i]);                    index[0] = k;                    index[1] = i;                    return index;                }            }else {                if(hashMap.containsKey(target-nums[i])){                    int k = hashMap.get(target-nums[i]);                    index[0] = k;                    index[1] = i;                    return index;                }                hashMap.put(nums[i], i);            }        }        return index;    }}
1 0