zoukankan      html  css  js  c++  java
  • [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;
        }
  • 相关阅读:
    ubuntu 下安装Angular2-cli脚手架
    git的使用及常用命令(二)
    framework7+node+mongo项目
    LINUX下安装搭建nodejs及创建nodejs-express-mongoose项目
    初学strurs基础
    JAVA Struts2 搭建
    mongodb的基本操作
    LightOj_1342 Aladdin and the Magical Sticks
    Codeforces Round #Pi (Div. 2)
    Codeforces Round #315 (Div. 2)
  • 原文地址:https://www.cnblogs.com/stAr-1/p/8366094.html
Copyright © 2011-2022 走看看