LeetCode

 
1. Two Sum
Easy
9870320FavoriteShare

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

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

	}
};

  

2. Add Two Numbers
Medium
46031146FavoriteShare

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

class Solution {
public:
	ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
		ListNode* h = new ListNode((l1->val + l2->val) % 10);
		ListNode* q = h;
		int qq=0;
		while (l1->next&&l2->next)
		{
			qq = (l1->val + l2->val) / 10;
			l1 = l1->next;
			l2 = l2->next;
			l1->val += qq;
			q->next = new ListNode((l1->val + l2->val) % 10);
			q = q->next;
		}
		qq = (l1->val + l2->val) / 10;
		if (l1->next)
		{
			l1->next->val = l1->next->val + (l1->val + l2->val) / 10;

			q->next = l1->next;
			l1 = l1->next;
			while (l1->val / 10)
			{
				l1->val %= 10;
				if (l1->next)
				{
					l1->next->val += 1;
					l1 = l1->next;
				}
				else
				{
					l1->next = new ListNode(1);
				}
			}
			return h;

		}
		if (l2->next)
		{
			l2->next->val = l2->next->val + (l2->val + l1->val) / 10;

			q->next = l2->next;
			l2 = l2->next;
			while (l2->val / 10)
			{
				l2->val %= 10;
				if (l2->next)
				{
					l2->next->val += 1;
					l2 = l2->next;
				}
				else
				{
					l2->next = new ListNode(1);
				}
			}
			return h;

		}
		if (qq)
			q->next = new ListNode(1);
		return h;


	}
};

  

 

3. Longest Substring Without Repeating Characters
Medium
4894252FavoriteShare

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.


class Solution {
public:
	int lengthOfLongestSubstring(string s) {
		if (!s.size())return 0;
		int a[300];
		for (int i = 0; i<300; ++i)
			a[i] = -1;
		int Max_data = 0;
		int k = 0;
		for (int i = 0; i<s.size(); ++i)
		{
			if (a[s[i]] == -1)
			{
				a[s[i]] = i;

			}
			else
			{
				Max_data = max(Max_data, i-k);

				k =max(k, a[s[i]]+1);
				a[s[i]] = i;
			}
		}
		Max_data = max(Max_data, static_cast<int>(s.size())- k);
		return Max_data;
	}
};

  

4. Median of Two Sorted Arrays
Hard
3804494FavoriteShare

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

Example 2:

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

The median is (2 + 3)/2 = 2.5
求第k大
class Solution {
public:
	double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
		int n1 = nums1.size();
		int n2 = nums2.size();
		if (n1 == 0)return (nums2[(n2) / 2] + nums2[(n2 - 1) / 2]) / 2.0;
		if (n2 == 0)return (nums1[(n1) / 2] + nums1[(n1 - 1) / 2]) / 2.0;
		if ((n1 + n2) % 2)return find_kth(nums1, 0, nums1.size(), nums2, 0, nums2.size(), (n1 + n2 + 1) / 2);
		return (
			find_kth(nums1, 0, nums1.size(), nums2, 0, nums2.size(), (n1 + n2 + 1) / 2)
			+ find_kth(nums1, 0, nums1.size(), nums2, 0, nums2.size(), (n1 + n2 + 2) / 2)
			) / 2.0;
	}
	int find_kth(vector<int>& nums1, int begin1, int size1, vector<int>& nums2, int begin2, int size2, int k)
	{
		size1 = min(k, size1);//第k大最多只要前k个
		size2 = min(k, size2);
		if (k == 1)
		{
			return min(nums1[begin1], nums2[begin2]);
		}
		if (size1 == 1)
		{
			if (begin2 + k - 1 < nums2.size())
				return min(max(nums1[begin1], nums2[begin2 + k - 2]), nums2[begin2 + k - 1]);
			else
				return max(nums1[begin1], nums2[begin2 + k - 2]);
		}
		if (size2 == 1)
		{
			if (begin1 + k - 1 < nums1.size())
				return min(max(nums2[begin2], nums1[begin1 + k - 2]), nums1[begin1 + k - 1]);
			else
				return max(nums2[begin1], nums1[begin1 + k - 2]);
		}
		double s = k / static_cast<double>(size1 + size2);//对应的比例位置
		int	q = s*(size1)+begin1;/**/
		int	p = s*(size2)+begin2;/**/
		if (static_cast<int>(s*(size1)) + static_cast<int>(s*(size2))> k - 1 && (q - begin1) && (p - begin2))
			//调节使 k刚好落在p 或 k
		{
			--p;
			--q;
		}
		if (static_cast<int>(s*(size1)) + static_cast<int>(s*(size2))< k - 3 && (q - begin1) && (p - begin2))
			//调节使 k刚好落在p 或 k
		{
			++p;
			++q;
		}
		if (nums1[q] > nums2[p])
		{
			k = k - (p - begin2);
			size1 = q - begin1 + 1;
			size2 -= (p - begin2);
			begin2 = p;
		}
		else
		{
			if (nums1[q] < nums2[p])
			{
				k = k - (q - begin1);
				size1 -= (q - begin1);
				begin1 = q;
				size2 = p - begin2 + 1;
			}
			else
			{
				return nums1[q];
			}
		}
		return find_kth(nums1, begin1, size1, nums2, begin2, size2, k);
	}
};

  

 

5. Longest Palindromic Substring
Medium
3088303FavoriteShare

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"
马拉车
class Solution {
public:
	string longestPalindrome(string s) {
		string ss;
		ss.resize(2 * s.size() + 1);
		for (int i = 0; i < s.size(); ++i)
		{
			ss[2 * i] = '+';
			ss[2 * i + 1] = s[i];
		}
		ss[2 * s.size()] = '+';
		vector<int> len;
		len.resize(ss.size() + 1, 0);
		int mid = 1;
		int end = 2;
		len[0] = 1;
		len[1] = 2;
		int max_i = 1;
		int max_ii = 2;
		int q = 1;
		for (int i = 2; i < ss.size(); ++i)
		{		
			q = 1;
			if (i <= end)
			{
				len[i] = len[2 * mid - i];
				if (i + len[i] < end)
					continue;
				else
				{
					q = end-i+1;
				}
			}
			while ((i - q) > -1 && i + q < ss.size() && ss[i - q] == ss[i + q])
				++q;
			len[i] = q;
			if (len[i] + i - 1 > end)
			{
				end = len[i] + i - 1;
				mid = i;
			}

			if (max_ii <= len[i])
			{
				max_ii = len[i];
				max_i = i;
			}


		}
		if (!(max_i % 2))
			return s.substr(max_i / 2 - max_ii / 2, max_ii - 1);
		return s.substr(max_i / 2 - max_ii / 2 + 1,(2* max_ii - 1)/2);
	}
};

  

6. ZigZag Conversion
Medium
9182851FavoriteShare

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

class Solution {
public:
	string convert(string s, int numRows) {
		char **q;
		q = new char*[numRows];
		for (int i = 0; i < numRows; ++i)
		{
			q[i] = new char[s.size()];
			for (int j = 0; j < s.size(); ++j)
			{
				q[i][j] = '*';
			}
		}
		int n = 0;
		int low = 0;
		while (n != s.size())
		{
			for (int i = 0; i < numRows&&n != s.size(); ++i, ++n)
			{
				q[i][low] = s[n];
			}
			for (int i = numRows - 2; i > 0 && n != s.size(); --i, ++n)
			{
				q[i][++low] = s[n];
			}
			++low;
		}
		string ss;
		ss.resize(s.size());
		n = 0;
		for (int i = 0; i < numRows; ++i)
		{
			for (int j = 0; j < s.size(); ++j)
			{
				if (q[i][j] != '*')
					ss[n++] = q[i][j];
			}
		}

		return ss;
	}
};

  

 

7. Reverse Integer
Easy
19602904FavoriteShare

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

class Solution {
public:
    int reverse(int x) {
        int t=0;
        t+=x%10;
        int aa=INT_MAX/10;
        int bb=INT_MIN/10;
        while(x/=10)
        {
            if(t>aa)return 0;
            if(t<bb)return 0;
            t*=10;
            t+=x%10;
        }
        return t;
    }
};

  

8. String to Integer (atoi)
Medium
8255305FavoriteShare

Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

  • Only the space character ' ' is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

class Solution {
public:
	int myAtoi(string str) {
		long long n = 0;
		int f = 0;
		for (int i = 0; i<str.size(); ++i)
		{
			if (str[i] == ' '&&!f)
				continue;

			if (f==0)
			{
				if (str[i] == '+')
				{
					f=1;				
                    continue;
				}
				if (str[i] == '-')
				{
					f = -1;				
                    continue;
				}
			}
			if ('0' <= str[i] && str[i] <= '9')
			{		
				if (!f)f = 1;
				if (n > INT_MAX + 1LL)
					break;
				n *= 10;
				n += str[i] - '0';
				continue;
			}
			break;
		}
		if(f==-1)
		if (n > INT_MAX+1LL)
				return INT_MIN;
		if (f == 1)
			if (n > INT_MAX)
				return INT_MAX;
		return f*n;
	}
};

  

9. Palindrome Number
Easy
12581227FavoriteShare

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0)return 0;
        if(x<10)return 1;

        int n=0;
        int i=1;
        int qq=x;
        while(x/=10)
        {
            i*=10;
        }
        x=qq;
        int q=10;
        while(i>9)
        {
            if(qq/i%10!=x%10)
                return 0;
            x/=10;
            i/=10;    
        }
        return 1;
    }
};

  

 



 















转载于:https://www.cnblogs.com/l2017/p/10447162.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值