leetcode_给定一个整数数组,返回两个数字的索引,使其和等于特定的数

第一次书写答案时间复杂度为n^2,空间复杂度为1

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] arr1=new int[2];
       // Arrays.sort(nums);
     ko: for(int j=0;j<nums.length-1;j++){
            for(int i=j+1;i<=nums.length-1;i++){ 
                if(target==nums[i]+nums[j]){
                    arr1[0]=j;
                    arr1[1]=i;
                   break ko;
                }
            }
        }
         return arr1;
    }
}

更好的解决方案为,时间复杂度n,空间复杂度为n

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            int mm=target-nums[i];
            if(map.containsKey(mm)){
                return new int[]{map.get(mm),i};
            }
            map.put(nums[i],i);
        }
        return null;
    }
}

猜你喜欢

转载自blog.csdn.net/wangci0211/article/details/88062153