LeetCode 数组(一)

目录

1. Two Sum

4.Median of Two Sorted Arrays    

11.Container With Most Water

15. 3Sum

16. 3Sum Closest

18. 4Sum

26. Remove Duplicates from Sorted Array

 27. Remove Element

33. Search in Rotated Sorted Array

34. 在排序数组中查找元素的第一个和最后一个位置


 

1. Two Sum

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].

思路:

A.暴力求解

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        vector<int>res;
        int len=nums.size();
        for(int i=0;i<len;i++)
        {
            for(int j=i+1;j<len;j++)
            {
                if((nums[i]+nums[j])==target)
                {
                    res.push_back(i);
                    res.push_back(j);
                    return res;
                }
            }
        }
        return res;
    }
};

B.双指针

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) 
	{
		vector<int> tmp = nums;
		int low = 0, hight = tmp.size()-1;
		sort(tmp.begin(), tmp.end());
		while (low < hight) {
			int s = tmp[low]+tmp[hight];
			if (s > target)
				hight--;
			else if (s < target)
				low++;
			else
				break;
		}
		vector<int> nResult;
		for (unsigned int i=0; i<nums.size(); i++) {
			if (nums[i] == tmp[low])
				nResult.push_back(i);
			else if (nums[i] == tmp[hight])
				nResult.push_back(i);
		}
		return nResult;

	}
};

C.哈希表

#include<vector>
#include<unordered_map>

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) 
	{
		unordered_map<int, int> m;//创建
		vector<int >nResult;
		for(int i=0;i<nums.size();i++)
		{
			m[nums[i]] =i;//键值key
		}
		for(int i=0;i<nums.size();i++)
		{
			int tmp = target-nums[i];
			if(m.count(tmp) && m[tmp]!=i)//判断是否满足条件
			{//主键元素个数 m.count(tmp)
				nResult.push_back(i);
				nResult.push_back(m[tmp]);
				break;
			}
		}
		return nResult;
	}
};

对于一上三种方法:

4.Median of Two Sorted Arrays    

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

You may assume nums1 and nums2 cannot be both empty.

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

思路一:

想到将两个数组重新 排序,合并之后中间元素则为中位数。归并排序复杂度大于 O(log (m+n)),但是LeetCode 运行通过了[捂脸]

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
    {
        int nLen1 = nums1.size();
        int nLen2 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值