码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]TwoSum系列问题

时间:2018-01-27 17:19:19      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:bool   empty   null   contains   遍历   false   while   pre   中序   

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;
    }

 

[leetcode]TwoSum系列问题

标签:bool   empty   null   contains   遍历   false   while   pre   中序   

原文地址:https://www.cnblogs.com/stAr-1/p/8366094.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!