打卡四

1.两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++)
{
if(int[i]+int[j]==target)
{
return new int[]{i,j};
}
}
}
throw new IllegalArgumentException(“No two sum solution”);
}
}
2.三数之和
class Solution{
public List<List> threeSum(int[] nums) {
List<List> result = new ArrayList<List>();
Arrays.sort(nums);

    for (int i = 0; i < nums.length-2; i++) {
        int left = i + 1;
        int right = nums.length - 1;
        if (i > 0 && nums[i] == nums[i - 1])
            continue; 
        while (left < right) {
            int sum = nums[left] + nums[right] + nums[i];
            if (sum == 0) {
                result.add(Arrays.asList(new Integer[]{nums[i], nums[left], nums[right]}));
                while (left < right && nums[left] == nums[left + 1])
                    left++; 
                while (left < right && nums[right] == nums[right - 1])
                    right--; 
                right--; 
                left++;
            } else if (sum > 0) {
                right--; 
            } else {
                left++; 
            }
        }
    }
    return result;
}

}
3.最接近的三数之和
class Solution(object):
def threeSumClosest(self, nums, target):
“”"
:type nums: List[int]
:type target: int
:rtype: int
“”"
nums.sort()
res = sum(nums[:3])
for i in range(len(nums)):
left = i+1
right = len(nums)-1
while left<right:
temp = nums[i]+nums[left]+nums[right]
if abs(res-target) > abs(temp-target):
res = temp
if temp>target:
right = right-1
else:
left = left+1
return res

4.四数之和
class Solution {
public List<List> fourSum(int[] nums, int target) {
List<List> ans = new ArrayList();
int len = nums.length;
Arrays.sort(nums);

if (nums == null || len < 4)
	return ans;

for (int i = 0; i < len - 3; i++) {
	if (i > 0 && nums[i] == nums[i - 1])
		continue;
	for (int j = i + 1; j < len - 2; j++) {
		if (j > i + 1 && nums[j] == nums[j - 1])
			continue;
		int L = j + 1;
		int R = len - 1;

		while (L < R) {
			int sum = nums[i] + nums[j] + nums[L] + nums[R];

			if (sum == target) {
				ans.add(Arrays.asList(nums[i], nums[j], nums[L], nums[R]));
				while (L < R && nums[L] == nums[L + 1])
					L++;
				while (L < R && nums[R] == nums[R - 1])
					R--;
				L++;
				R--;
			} else if (sum > target)
				R--;
			else if (sum < target)
				L++;

		}
	}
}
return ans;

}
}
5.字母异位词分组
class Solution:
def groupAnagrams(self, strs):
“”"
:type strs: List[str]
:rtype: List[List[str]]
“”"
strs_map = {}
result = []
for i in strs:
string = ‘’.join(sorted(i))
if string not in strs_map:
strs_map[string] = len(result)
result.append([i])
else:
result[strs_map[string]].append(i)
return result
6.直线上的点数
class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
if len(points) <= 2:
return len(points)
maxNum = 0
for i in range(len(points)):
maxNum = max(maxNum,self.find(points[i],points[:i]+points[i+1:]))
return maxNum + 1
def find(self,point,pointList):
memories = {}
count = 0
inf = float(“inf”)
for curPoint in pointList:
if curPoint[1] == point[1] and curPoint[0] != point[0]:
memories[inf] = memories.get(inf,0) + 1
elif curPoint[1] == point[1] and curPoint[0] == point[0]:
count += 1
else:
slope = (curPoint[0] - point[0]) / (curPoint[1] - point[1])
memories[slope] = memories.get(slope,0) + 1
if memories:
return count + max(memories.values())
else:
return count
7.存在重复元素二
class Solution:
def containsNearbyDuplicate(self, nums, k):
“”"
:type nums: List[int]
:type k: int
:rtype: bool
“”"
d = {}
for i in range(len(nums)):
if nums[i] in d:
if -k <= i - d[nums[i]] <= k:
return True
else:
d[nums[i]] = i
d[nums[i]] = i
return False
8.存在重复元素三
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) {
int size = nums.size();
map<long, int> m;
map<long, int>::iterator it;
for(int i = 0; i < size; i++){
it = m.lower_bound((long)nums[i] - t);
while(it != m.end()){
if((long)it->first - t > nums[i]) break;
if(i - it->second <= k) return true;
it++;
}
m[nums[i]] = i;
}
return false;
}
};
9.回旋镖的数量
class Solution(object):
def numberOfBoomerangs(self, points):
“”"
:type points: List[List[int]]
:rtype: int
“”"
res = 0
for i in points:
record = dict()
for j in points:
if i != j:
record[self.dis(i, j)] = 0
for j in points:
if i != j:
record[self.dis(i, j)] = record[self.dis(i, j)] + 1

        for key in record:
            res = res + record[key]*(record[key] - 1)
    
    return res


def dis(self, pointa, pointb):
    return (pointa[0] - pointb[0])*(pointa[0] - pointb[0]) + (pointa[1] - pointb[1])*(pointa[1] - pointb[1])

10.四数相加二
class Solution(object):
def fourSumCount(self, A, B, C, D):
“”"
:type A: List[int]
:type B: List[int]
:type C: List[int]
:type D: List[int]
:rtype: int
“”"
m = {}
n = len(A)
for i in xrange(n):
for j in xrange(n):
m[A[i] + B[j]] = m.get(A[i] + B[j], 0) + 1
res = 0
for i in xrange(n):
for j in xrange(n):
res += m.get(-(C[i] + D[j]), 0)
return res

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值