Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
My code:
import numpy as np
class Solution:
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
index=np.argsort(nums)
result=[]
for i in range(len(nums)-3):
if i>=1:
if nums[index[i]]==nums[index[i-1]]:
continue
for j in range(i+1,len(nums)-2):
if j>=i+2:
if nums[index[j]]==nums[index[j-1]]:
continue
require=target-nums[index[i]]-nums[index[j]]
lstart=j+1
rstart=len(nums)-1
while lstart<rstart:
number1=nums[index[lstart]]
number2=nums[index[rstart]]
#print('lstart %d value %d'%(lstart,number1))
if number1+number2==require:
result.append([nums[index[i]],nums[index[j]],number1,number2])
while nums[index[lstart+1]]==nums[index[lstart]] and lstart+1<rstart:
lstart+=1
while nums[index[rstart-1]]==nums[index[rstart]] and rstart-1>lstart:
rstart-=1
lstart+=1
rstart-=1
elif number1+number2>require:
rstart-=1
else:
lstart+=1
return result
Solution:
https://leetcode.com/problems/4sum/