算法练习(哈希与映射)

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

猜你喜欢

转载自blog.csdn.net/cy1798/article/details/114362409