Skip to content

Instantly share code, notes, and snippets.

@dasider41
Created September 5, 2019 20:32
Show Gist options
  • Save dasider41/dd67c14ee5314a0c5c01f3a671109e48 to your computer and use it in GitHub Desktop.
Save dasider41/dd67c14ee5314a0c5c01f3a671109e48 to your computer and use it in GitHub Desktop.
<?php
/*
https://leetcode.com/problems/two-sum/submissions/
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
*/
function twoSum(array $nums, int $target): array
{
$length = count($nums) - 1;
for ($i = 0; $i <= $length; $i++) {
for ($j = $i + 1; $j <= $length; $j++) {
$sumResult = $nums[$i] + $nums[$j];
if ($sumResult === $target) {
return [$i, $j];
}
}
}
return [];
}
// /Test code 1
$nums = [2, 7, 11, 15];
$target = 9;
var_dump(twoSum($nums, $target) === [0, 1]);
// /Test code 2
$nums = [3, 2, 4];
$target = 6;
var_dump(twoSum($nums, $target) === [1, 2]);
// /Test code 3
$nums = [2, 5, 5, 11];
$target = 10;
var_dump(twoSum($nums, $target) === [1, 2]);
@dasider41
Copy link
Author

Better way

function twoSum(array $nums, int $target): array
{
    foreach ($nums as $key => $val) {
        unset($nums[$key]);
        $nextKey = array_search(($target - $val), $nums);
        if ($nextKey) {
            return [$key, $nextKey];
        }
    }
    return [];
}

@Robotboy93
Copy link

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:

    a= b = 0
    
    for i in range(len(nums)):
        c = nums[i]
        del nums[i]
        if (target-c) in nums:
            a = i
            
            b = (nums.index((target-c)))
        nums.insert(i,c)
    result = [b,a]

    return result
    pass

ret = Solution().twoSum([1,2,3,4,5,6,7],8)

print(ret)

@developeralamin
Copy link

developeralamin commented May 6, 2024

class Solution {

/**
 * @param Integer[] $nums
 * @param Integer $target
 * @return Integer[]
 */
function twoSum($nums, $target) {
    for($i=0; $i < count($nums); $i++){
        for($j = $i + 1; $j<count($nums); $j++){
            if($nums[$i] + $nums[$j] == $target){
                return [$i,$j];
            }
        }
    }
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment