fork download
  1. //Enter you code here.
  2. //Please indent properly.
  3. const twoSum = (nums, target) => {
  4. const map = {};
  5.  
  6. for (let i = 0; i < nums.length; i++) {
  7. const another = target - nums[i];
  8.  
  9. if (another in map) {
  10. return [map[another], i];
  11. }
  12.  
  13. map[nums[i]] = i;
  14. }
  15.  
  16. return null;
  17. };
  18. <?php
  19. //program to find the common elements of the two array
  20. //here we have to array A and B from which w have to find the common element
  21. //first we sort then using merge sort and after then for traversing through
  22. //the array in one iteration we can find the comman elements the given array
  23. //this is an inspace algorithm meansno extra space is needed
  24.  
  25. //best case time complexity=O(nlogn)
  26. //O(nlogn)-> for sorting
  27. //O(n)-> for while loop to find comman element
  28.  
  29. //average case time complexity=O(nlogn)
  30. //O(nlogn)-> for sorting
  31. //O(n)-> for while loop to find comman element
  32.  
  33. //worst case time complexity =O(nlogn)
  34. //O(nlogn)-> for sorting
  35. //O(n)-> for while loop to find comman element
  36.  
  37.  
  38.  
  39. $commonArray=array();
  40. $A=array(3,4,5,6,7,8,9,10,36,58,27,48);
  41. $B=array(3,10,4,5,6,8,12,24,37,27,50);
  42. sort($A);
  43. sort($B);
  44. $size1=sizeof($A);
  45. $size2=sizeof($B);
  46. $counter1=0;
  47. $counter2=0;
  48. while(($counter1< $size1) && ($counter2)<($size2))//traversing through the array
  49. {
  50.  
  51. if ($A[$counter1] == $B[$counter2])
  52. {
  53. array_push($commonArray,$A[$counter1]); //to enter comman element in the output array
  54. $counter1=$counter1+1;
  55. $counter2=$counter2+1;
  56. }
  57. else if ($A[$counter1] < $B[$counter2])
  58. {
  59. $counter1=$counter1+1; }
  60.  
  61. else
  62. {
  63. $counter2=$counter2+1;
  64. }
  65. }
  66.  
  67. print_r($commonArray);//to print the output array
  68. ?>
  69.  
  70.  
Success #stdin #stdout 0.02s 26244KB
stdin
Standard input is empty
stdout
//Enter you code here.
//Please indent properly.
const twoSum = (nums, target) => {
  const map = {};

  for (let i = 0; i < nums.length; i++) {
    const another = target - nums[i];

    if (another in map) {
      return [map[another], i];
    }

    map[nums[i]] = i;
  }

  return null;
};
Array
(
    [0] => 3
    [1] => 4
    [2] => 5
    [3] => 6
    [4] => 8
    [5] => 10
    [6] => 27
)