146. LRU Cache | It's Showing "Time Limit Exceeded" after submitting the code


  • 0
    M

    Hi guys, anyone faced this before with any other problem. It says that till the last test case it passed but code is not efficient and hence it took long. Please have a look at my code and please suggest to make it better (btw this was my first try to submit the code)

    '''
    public class LRUCache {

    private int capacity;
    private ArrayList<DataObject> LRUCacheList;
    
    class DataObject{
        Object key;
        Object value;
        
        DataObject(Object key, Object value){
            this.key = key;
            this.value = value;
        }
        
        public boolean equals(DataObject otherDataObject){
            if (this.key.equals(otherDataObject.key))
                return true;
            return false;
        }
        
        public String toString(){
        	return "{ " + key + " : " + value + " }";
        }
    }
    
    public LRUCache(int capacity) {
        this.capacity = capacity;
        LRUCacheList = new ArrayList<DataObject>();
    }
    
    public int getCapacity(){
        return capacity;
    }
    
    public String toString(){
    	StringBuffer buffer = new StringBuffer("MY LRU Cache: \n");
    	for(DataObject curObj : LRUCacheList){
    		buffer.append(curObj.toString() + "\n");
    	}
    	return buffer.toString();
    }
    
    public int get(int key) {
        DataObject newDataObject = new DataObject(key,null);
    	for (DataObject curObject : LRUCacheList){
            if (curObject.equals(newDataObject)){
            	DataObject temp = curObject;
            	LRUCacheList.remove(curObject);
            	LRUCacheList.add(temp);
                return (int)temp.value;
            }
        }
    	return -1;
    }
    
    public void set(int key, int value) {
    
    	DataObject newDataObject = new DataObject(key,value);
        
        for (DataObject curObject : LRUCacheList){
            if (curObject.equals(newDataObject)){
                LRUCacheList.remove(curObject);
                break;
            }
        }
        
        if (LRUCacheList.size() == capacity)
            LRUCacheList.remove(0);
        
        LRUCacheList.add(newDataObject);
    }
    

    }
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.