数组-leetcode 1. Two Sum

来源:互联网 发布:安心360定位软件 编辑:程序博客网 时间:2024/05/23 13:35

原题链接:Two Sum


题解:

public class Solution {    public int[] twoSum(int[] nums, int target) {        /*            Time Complexity:O(n)            Space Complexity:O(n)        */        int[] res=new int[2];        if(nums==null || nums.length<2)return res;        HashMap<Integer,Integer>hashMap=new HashMap<>();        for(int i=0;i<nums.length;i++){            if(hashMap.containsKey(nums[i])){                res[0]=hashMap.get(nums[i]);                res[1]=i;                break;            }            else{                hashMap.put(target-nums[i],i);            }        }        return res;    }}



旁白:因业务需要转java,特用java刷lc,觉得写习惯了c++写java很不方便,还是觉得c++用起来舒服,可能是习惯了c++并且对java还不熟吧。

原创粉丝点击