1. 两数之和(leetcode)

解题思路:

第一个方法是穷举,第二个方法是利用Map做,第二个方法一开始没想到,还是有点太年轻。

代码:

第一个代码:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ans = new int[2];
        boolean flag = false;
        for(int i=0;i<nums.length;i++) {
            for(int j=0;j<nums.length;j++){
                if(i == j){
                    continue;
                }else{
                    if(nums[i] + nums[j] == target){
                        ans[0] = i;
                        ans[1] = j;
                        flag = true;
                        break;
                    }
                }
            }
            if(flag){
                break;
            }
        }
        
        
        return ans;
    }
}

第二个代码:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();
        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[1];
    }
}
原文地址:https://www.cnblogs.com/doubest/p/10467207.html