Leetcode面T16(20-26)树

Q16.21  交换和

给定两个整数数组,请交换一对数值(每个数组中取一个数值),使得两个数组所有元素的和相等。

返回一个数组,第一个元素是第一个数组中要交换的元素,第二个元素是第二个数组中要交换的元素。若有多个答案,返回任意一个均可。若无满足条件的数值,返回空数组。

示例:

输入: array1 = [4, 1, 2, 1, 1, 2], array2 = [3, 6, 3, 3]
输出: [1, 3]
示例:

输入: array1 = [1, 2, 3], array2 = [4, 5, 6]
输出: []
提示:

1 <= array1.length, array2.length <= 100000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-swap-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

交换之后,两组和相等,所以两组总和一定是偶数。假设arr1的和为sum1,arr2的和为sum2,有avg = (sum1+sum2)/2;则avg是交换后每个数组的和。如果sum1<=avg,那么只要arr1中存在元素x,使得x+(avg-sum1)==arr2中某个元素,即说明可以交换一对值,使和相等,sum2<=avg也一样。

class Solution {
    public int[] findSwapValues(int[] array1, int[] array2) {
        int sum1 = 0;
        int sum2 = 0;
        for(int num1 : array1)
            sum1 += num1;
        
        Set<Integer> set = new HashSet<>();
        for(int num2 : array2)
            {
                sum2 += num2;
                set.add(num2);
            }
        
        int avg = (sum1 + sum2) / 2;
        
        if(avg * 2 != sum1 + sum2)
            return new int[]{};
        int t = Math.abs(sum1 - avg);
        if(sum1 > avg)
            t =-t;

        for(int num : array1)
            if(set.contains(num + t))
                return new int[]{num, num+t};
        
         return new int[]{};
    }
}

Q16.22  兰顿蚂蚁

一只蚂蚁坐在由白色和黑色方格构成的无限网格上。开始时,网格全白,蚂蚁面向右侧。每行走一步,蚂蚁执行以下操作。

(1) 如果在白色方格上,则翻转方格的颜色,向右(顺时针)转 90 度,并向前移动一个单位。
(2) 如果在黑色方格上,则翻转方格的颜色,向左(逆时针方向)转 90 度,并向前移动一个单位。

编写程序来模拟蚂蚁执行的前 K 个动作,并返回最终的网格。

网格由数组表示,每个元素是一个字符串,代表网格中的一行,黑色方格由 'X' 表示,白色方格由 '_' 表示,蚂蚁所在的位置由 'L', 'U', 'R', 'D' 表示,分别表示蚂蚁 左、上、右、下 的朝向。只需要返回能够包含蚂蚁走过的所有方格的最小矩形。

示例 1:

输入: 0
输出: ["R"]
示例 2:

输入: 2
输出:
[
  "_X",
  "LX"
]
示例 3:

输入: 5
输出:
[
  "_U",
  "X_",
  "XX"
]
说明:

K <= 100000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/langtons-ant-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

public List<String> printKMoves(int K) {
        int[][] arr = new int[4000][4000];
        int minx = Integer.MAX_VALUE, miny = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE, maxY = Integer.MIN_VALUE;
        List<String> res = new ArrayList<>();
        if (K == 0) {
            res.add("R");
            return res;
        }
        int x = 2000, y = 2000;
        char pos = 'R';
        minx = Math.min(minx, x);
        miny = Math.min(miny, y);
        maxX = Math.max(maxX, x);
        maxY = Math.max(maxY, y);
        while (K > 0) {
            int prex = x, prey = y;
            if (arr[x][y] == 0) {
                if (pos == 'R') {
                    x += 1;
                    pos = 'D';
                } else if (pos == 'D') {
                    y -= 1;
                    pos = 'L';
                } else if (pos == 'L') {
                    x -= 1;
                    pos = 'U';
                } else {
                    y += 1;
                    pos = 'R';
                }
            } else {
                if (pos == 'R') {
                    x -= 1;
                    pos = 'U';
                } else if (pos == 'U') {
                    y -= 1;
                    pos = 'L';
                } else if (pos == 'L') {
                    x += 1;
                    pos = 'D';
                } else {
                    y += 1;
                    pos = 'R';
                }
            }
            arr[prex][prey] = arr[prex][prey] == 1 ? 0 : 1;
            K--;
            minx = Math.min(minx, x);
            miny = Math.min(miny, y);
            maxX = Math.max(maxX, x);
            maxY = Math.max(maxY, y);
        }
        for (int i = minx; i <= maxX; i++) {
            StringBuilder sb = new StringBuilder();
            for (int j = miny; j <= maxY; j++) {
                if (i == x && j == y) {
                    sb.append(pos);
                } else {
                    if (arr[i][j] == 0) sb.append("_");
                    else sb.append("X");
                }
            }
            res.add(sb.toString());
        }
        return res;
    }

Q16.24 数对和

设计一个算法,找出数组中两数之和为指定值的所有整数对。一个数只能属于一个数对。

示例 1:

输入: nums = [5,6,5], target = 11
输出: [[5,6]]
示例 2:

输入: nums = [5,6,5,6], target = 11
输出: [[5,6],[5,6]]
提示:

nums.length <= 100000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pairs-with-sum-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

public List<List<Integer>> pairSums(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        int l = 0, r = nums.length-1;
        while (l<r){
            if(nums[l] + nums[r] == target){
                List<Integer> list = new ArrayList<>();
                list.add(nums[l]);
                list.add(nums[r]);
                res.add(list);
                l++; r--;
            }else if(nums[l] + nums[r] > target) r--;
            else l++;
        }
        return res;
    }

Q16.25 LRU 缓存

设计和构建一个“最近最少使用”缓存,该缓存会删除最近最少使用的项目。缓存应该从键映射到值(允许你插入和检索特定键对应的值),并在初始化时指定最大容量。当缓存被填满时,它应该删除最近最少使用的项目。

它应该支持以下操作: 获取数据 get 和 写入数据 put 。

获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。

示例:

LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // 返回  1
cache.put(3, 3);    // 该操作会使得密钥 2 作废
cache.get(2);       // 返回 -1 (未找到)
cache.put(4, 4);    // 该操作会使得密钥 1 作废
cache.get(1);       // 返回 -1 (未找到)
cache.get(3);       // 返回  3
cache.get(4);       // 返回  4

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lru-cache-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class LRUCache {
        Map<Integer, Integer> map;
        int capacity;
        public LRUCache(int capacity) {
            map = new LinkedHashMap<>(capacity);
            this.capacity = capacity;
        }
        public int get(int key) {
            if (!map.containsKey(key))
                return -1;
            int value = map.get(key);
            map.remove(key);
            map.put(key, value);
            return value;
        }
        public void put(int key, int value) {
            if (map.containsKey(key)) {
                map.remove(key);
                map.put(key, value);
            } else {
                if (map.size() == capacity)
                    map.remove(map.keySet().iterator().next());
                map.put(key, value);
            }
        }
    }

Q16.26 计算器

给定一个包含正整数、加(+)、减(-)、乘(*)、除(/)的算数表达式(括号除外),计算其结果。

表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格  。 整数除法仅保留整数部分。

示例 1:

输入: "3+2*2"
输出: 7
示例 2:

输入: " 3/2 "
输出: 1
示例 3:

输入: " 3+5 / 2 "
输出: 5
说明:

你可以假设所给定的表达式都是有效的。
请不要使用内置的库函数 eval。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/calculator-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 public int calculate(String s) {

        Stack<Integer> stack = new Stack<>();
        char opt = '+';
        int num = 0;

        for (int i = 0; i < s.length(); i++) {

            char ch = s.charAt(i);

            if (Character.isDigit(ch))
                num = num * 10 + (ch - '0');

            if ((!Character.isDigit(ch) && ch != ' ') || i == s.length() - 1) {

                if (opt == '+')
                    stack.push(num);
                else if (opt == '-')
                    stack.push(-num);
                else if (opt == '*') 
                    stack.push(stack.pop() * num);
                else    
                    stack.push(stack.pop() / num);
                
                num = 0;
                opt = ch;
            }
        }

        int res = 0;
        while (!stack.isEmpty())
            res += stack.pop();
        
        return res;
    }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值