力扣167.两数之和II-输入有序数组

import java.util.HashMap;
//法1:哈希表
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        HashMap map = new HashMap();
        for(int i = 0; i < numbers.length; i++) {
            if (map.containsKey(target - numbers[i])) {
                return new int[] {map.get(target - numbers[i]) + 1, i + 1};
            } else {
                map.put(numbers[i], i);
            }


        }
        return new int[] {-1, -1};
    }
}

//法2:双指针
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int l = 0;
        int r = numbers.length-1;
        // l不能取等于r,因为不能取重复的元素
        while(ltarget){
                r--;
            }else{
                l++;
            }
        }
        return new int[]{-1,-1};

    }
}

你可能感兴趣的:(算法与数据结构进阶(java),leetcode,算法,java)