[leetcode]TwoSum系列问题

1.普通数组找两个数,哈希表建立数值和下标的映射,遍历时一边判断一边添加

/*
    哇,LeetCode的第一题...啧啧
     */
    public int [] twoSum(int[] nums, int target) {
        /*
        两个数配合组成target
        建立值和下标的映射,遍历数组时一边判断是否有另一半,一边添加新映射到哈希表
         */
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int a = target-nums[i];
            if (map.containsKey(a))
                return new int[]{i,map.get(a)};
            map.put(nums[i],i);
        }
        return null;
    }

2.顺序数组,双指针分别靠向中间

public int[] twoSum(int[] num, int target) {
        /*
        two sum第二题,排序好的数组,双指针
         */
        int left = 0,right = num.length-1;
        while (left<right)
        {
            int a = num[left] + num[right];
            if (a == target)
                return new int[]{left+1,right+1};
            if (a > target)
                right--;
            else left++;
        }
        return null;
    }

3.BST,中序遍历后中上一题的做法做

public boolean findTarget(TreeNode root, int k) {
        /*
        中序遍历得到排序数组,然后就是two sum2的做法
         */
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty()||root!=null)
        {
            if (root!=null)
            {
                stack.push(root);
                root = root.left;
            }
            else {
                root = stack.pop();
                list.add(root.val);
                root = root.right;
            }
        }
        //下面开始挑选
        int l = 0,r = list.size()-1;
        while (l < r)
        {
            int a = list.get(l) + list.get(r);
            if (a==k) return true;
            if (a>k) r--;
            else l++;
        }
        return false;
    }

 

posted @ 2018-01-27 15:02  stAr_1  阅读(109)  评论(0编辑  收藏  举报