您的位置:首页 > Web前端

Difference between ArrayList and LinkedList in Java

2017-07-10 14:02 936 查看
      When practicing on Leetcode, I often utilize a common data structure: list, and there are two main types for list in java: ArrayList and LinkedList. So, what's the difference between them and how we choose between them when using list.



(from https://www.javatpoint.com/difference-between-arraylist-and-linkedlist)
From above picture, we learnt that these two implementations use different data structures internally. For ArrayList, it uses dynamic array, while LinkedList, double linked list. Based on this fact, it is easy to know, ArrayList is better for searching while
worse for inserting and removing; LinkedList is better for inserting and removing, while worse for searching. 

From the java doc, it says both of the implementations are
synchronized.

In the leetcode 380, one of the solution uses the ArrayList and wisely avoid its defect, it tries to insert and remove the element at the ending of the list.

public class RandomizedSet {

/** Initialize your data structure here. */
Mapmap;//val -> index
Listlist;

public RandomizedSet() {
map = new HashMap<>();
list = 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(!map.containsKey(val)){
list.add(val);
map.put(val, list.size() - 1);
return true;
}
else return false;
}

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

/** Get a random element from the set. */
public int getRandom() {
if(list.size() <= 0)
return -1;
return list.get(new Random().nextInt(list.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();
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java algorithm