每日一题(算法)

题目:两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

解法一(双重for循环)

时间复杂度O(n2)

空间复杂度O(1)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] index = new int[2];
        out:
        for(int i=0;i<nums.length;i++){
            int one = nums[i];
            for(int j=i+1;j<nums.length;j++){
                int two = nums[j];
                int total = one + two;
                if (total == target){
                    index[0] = i;
                    index[1] = j;
                    break out;
                }
            }
        }
        System.out.println(index);
        return index;
    }
}

解法二(hashMap)

时间复杂度O(n)

空间复杂度O(n)

解法二是采用了空间换时间的方式

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

        }
        return new int[0];
    }
}
原文地址:https://www.cnblogs.com/libinhyq/p/14871277.html