3 Sum

PHP

``````class Solution {

/**
* @param Integer[] \$nums
* @return Integer[][]
*/
function threeSum(\$nums) {
sort(\$nums);
\$count = count(\$nums);
\$result = [];
for (\$i = 0; \$i < \$count - 2; \$i++) {
\$j = \$i + 1;
\$k = \$count - 1;
while (\$j < \$k) {
\$sum = \$nums[\$i] + \$nums[\$j] + \$nums[\$k];
if (\$sum === 0) {
\$result[\$nums[\$i].",".\$nums[\$j].",".\$nums[\$k]] = [\$nums[\$i], \$nums[\$j], \$nums[\$k]];
\$j++;
\$k--;
} elseif (\$sum < 0) {
\$j++;
} else {
\$k--;
}
}
}
return \$result;
}
}``````

736 total views

Two Sum

JavaScript

``````/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
for(i in nums) {
for (j in nums) {
if (i < j && nums[i] + nums[j] == target) {
return [Number(i), Number(j)];
}
}
}
};``````

Python 3

``````class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}

for i, v in enumerate(nums):
if target - v in dict:
return [dict[target - v], i]
dict[v] = i``````

JavaScript

``````/**
* function ListNode(val) {
*     this.val = val;
*     this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {

sum = l3 = new ListNode(0);

while (l1 || l2) {
if (l1) {
l3.val += l1.val;
l1 = l1.next;
}

if (l2) {
l3.val += l2.val;
l2 = l2.next;
}

if (l3.val >= 10) {
l3.val -= 10;
l3.next = new ListNode(1);
l3 = l3.next;
} else if (l1 || l2) {
l3.next = new ListNode(0);
l3 = l3.next;
}
}

return sum;
};``````

Python3

``````# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""

while l1 or l2:
if l1:
l3.val += l1.val
l1 = l1.next

if l2:
l3.val += l2.val
l2 = l2.next

if l3.val >= 10:
l3.val -= 10
l3.next = ListNode(1)
l3 = l3.next
elif l1 or l2:
l3.next = ListNode(0)
l3 = l3.next