算法练习(哈希与映射)

1.在这里插入图片描述

//本质上是一个二十六进制的转化问题
public int titleToNumber(String s) {
        int n = s.length();
        int sum = 0;
        for (int i = 0; i < n; i++) {
            int temp = s.charAt(i) - 'A';
            sum = sum * 26 + temp;
        }
        return sum;
    }

2.在这里插入图片描述

//如果采用暴力求解,会超时,所以两两一组减少时间复杂度
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        int count = 0;
        for (int a : A) {
            for (int b : B) {
                hashMap.put(a + b, hashMap.getOrDefault(a + b, 0) + 1);
            }
        }

        for (int c : C) {
            for (int d : D) {
                if (hashMap.containsKey(-c - d)) {
                    count += hashMap.get(-c - d);
                }
            }
        }

        return count;
    }

3.在这里插入图片描述

//因为要保证平均O(1)的时间复杂度,所以要采用hashmap和arraylist,而一般的remove是线性时间的,为了保证O(1)时间复杂度,采取了将要删除元素转化为删除arraylist最后一个元素的做法;随机取数用Random。
class RandomizedSet {

        HashMap<Integer, Integer> IndexMap;
        ArrayList<Integer> list;
        Random random;

        /**
         * Initialize your data structure here.
         */
        public RandomizedSet() {
            IndexMap = new HashMap<>();
            list = new ArrayList<>();
            random = new Random();
        }

        /**
         * Inserts a value to the set. Returns true if the set did not already contain the specified element.
         */
        public boolean insert(int val) {
            if (IndexMap.containsKey(val)) {
                return false;
            }
            IndexMap.put(val, list.size());
            list.add(list.size(), val);
            return true;
        }

        /**
         * Removes a value from the set. Returns true if the set contained the specified element.
         */
        public boolean remove(int val) {
            if (!IndexMap.containsKey(val)) {
                return false;
            }
            int last = list.get(list.size() - 1);
            int index = IndexMap.get(val);
            list.set(index, last);
            IndexMap.put(last, index);
            list.remove(list.size() - 1);
            IndexMap.remove(val);
            return true;
        }

        /**
         * Get a random element from the set.
         */
        public int getRandom() {
            return list.get(random.nextInt(list.size()));
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值