Same code in JAVA and CPP , but the difference in running time is huge


  • 0
    R

    Hi,
    I wrote the following code in CPP that is accepted

    class Solution {
    public:

    vector<int> twoSum(vector<int>& nums, int target) {
    
        map<int,int> Map;
        vector<int> result(2);
        for(int i=0; i<nums.size(); ++i){
            if(Map.find(target-nums[i]) != Map.end()){
                    result[0] = Map[target-nums[i]];
                    result[1] = i + 1
                    break;
            }
            else{
                Map[nums[i]] = i+1;
            }
        }
    
        return result;
    }
    

    };

    And the following code in JAVA that is also accepted

    public class Solution {

    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer,Integer> map= new HashMap<Integer,Integer>();
        for(int i =0;i<nums.length; ++i){
           if(!map.containsKey(target-nums[i])){
                  result[0] = map.get(target-nums[i]);
                    result[1] = i+1
                    break;
            }
            else {
                  map.put(nums[i],i+1);
            }
    
        }
     return result;
    }
    

    }

    CPP code takes only 42 ms to execute where as JAVA code takes 350 ms . Does any one has idea about why this is happening? So much difference


  • 0
    W

    Generally, Java's efficiency is lower than CPP's, which means Java code takes more time.


Log in to reply
 

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