1. Two Sum

来源:互联网 发布:mmd h动作数据 编辑:程序博客网 时间:2024/05/22 14:52

题目:https://leetcode.com/problems/two-sum/

代码:

public class Solution {    public int[] twoSum(int[] nums, int target) {        int[] res = new int[2];        int length = nums.length;        temp:        for(int i=0;i<length;i++)        {            for(int j=i+1;j<length;j++)            {                if(nums[i]+nums[j]==target)                {                    res[0] = i;                    res[1] = j;                    break temp;                }            }        }        return res;    }}=================public class Solution {    public int[] twoSum(int[] nums, int target) {        HashMap<Integer,Integer> res = new HashMap<>();        for(int i=0;i<nums.length;i++)        {            Integer position = res.get(target-nums[i]);            if(position == null)                res.put(nums[i],i);            else                return new int[]{position,i};        }        return new int[2];    }}
0 0
原创粉丝点击