Leetcode 之 Insert Delete GetRandom O(1)

题目

Design a data structure that supports all following operations in average O(1) time.

  • insert(val): Inserts an item val to the set if not already present.

  • remove(val): Removes an item val from the set if present.

  • getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned

题意解析

要求实现上述的三个操作,且操作时间为O(1)的操作时间。使用HashMap保存输入的数字的index,用ArrayList保存数组。一个值得注意的问题是,有一个getRandom的操作,计划是根据Random类的nextInt方法来获得下标,然后从ArrayList中返回数据,故应该保持ArrayList中的index的连续的,一个简单的做法是将删除的元素由最后一个元素取代,并删除原最后元素,保证size-1;

Code

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

/**
 * Created by loveqh on 2016/8/9.
 */
public class RandomizedSet {

    private HashMap<Integer, Integer> hashMap;
    private ArrayList<Integer> arrayList;

    /**
     * Initialize your data structure here.
     */
    public RandomizedSet() {
        hashMap = new HashMap<>();
        arrayList = new ArrayList<>();
    }

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

    /**
     * Removes a value from the set. Returns true if the set contained the specified element.
     */
    public boolean remove(int val) {
        if (!hashMap.containsKey(val)) {
            return false;
        } else {
            // V = hashMap.remove(K)
            int index = hashMap.remove(val);
            /**
             * 要求getRandom的数据为连续 ,故将删除的位置和数组的最后一个元素填补
             */
            if (index < arrayList.size() - 1) {
                //用最后一个数取代index位置的元素
                arrayList.set(index, arrayList.get(arrayList.size() - 1));
                //修改KeyValue
                hashMap.put(arrayList.get(arrayList.size() - 1), index);
            }
            //删除最后一个元素
            arrayList.remove(arrayList.size() - 1);
            return true;
        }
    }

    /**
     * Get a random element from the set.
     */
    Random random = new Random();

    public int getRandom() {
        return arrayList.get(random.nextInt(arrayList.size()));
    }
}

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet obj = new RandomizedSet();
 * boolean param_1 = obj.insert(val);
 * boolean param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */

提交的时候一个值得注意的点

一定要在public class 前使用

import java.util.Random

不然会产生编译错误。我也真是服了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值