O(N^2) but TLE


  • 0
    L

    I use JavaScript and the algorithm time is O(N^2), but the results showed TLE, can anyone tell me why? thanks.

    /**
     * @param {number[][]} points
     * @return {number}
     */
    var numberOfBoomerangs = function(points) {
      let result = 0;
      let length = points.length;
      for (let i = 0; i < length; i++) {
        let hashMap = {};
        for (let j = 0; j < length; j++) {
          if (i === j) { continue; }
          let distance = Math.pow(points[i][0]-points[j][0], 2) + Math.pow(points[i][1] - points[j][1], 2);
          // hashMap[distance] represents the number of points with a distance of 'distance' to points[i]
          if (typeof hashMap[distance] === 'undefined') {
            hashMap[distance] = 1;
          }
          else {
            hashMap[distance]++;
          }
        }
        for (let distance in hashMap) {
          result += hashMap[distance] * (hashMap[distance] - 1);
        }
      }
      return result;
    };
    
    

Log in to reply
 

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