leetcode-array-easy-over

【53,119,213,268,414,448,485,532,561,566,581,605,628,643,665,674,697,717,724,746,747,766,830,849,867】

Given an integer array nums, find the contiguous subarray (containing
at least one number) which has the
largest sum and return its sum.
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.

int Solution53::maxSubArray(vector<int>& nums)
{
    //wonderful
    int maxSoFar = nums[0], maxEndingHere = nums[0];
    for (int i = 1; i<nums.size(); ++i) {
        maxEndingHere = max(maxEndingHere + nums[i], nums[i]);//如果累加到i没有当前值大,重新赋值,否则累加
        maxSoFar = max(maxSoFar, maxEndingHere);
    }
    return maxSoFar;
}

Given an array of integers and an integer k, find out whether there
are two distinct indices i and j in the array such that nums[i] =
nums[j] and the absolute difference between i and j is at most k.
Input: nums = [1,2,3,1], k = 3 Output: true Input: nums =
[1,2,3,1,2,3], k = 2 Output: false

bool Solution219::containsNearbyDuplicate(vector<int>& nums, int k)
{
    //way1
    //int len = nums.size();
    //if (len < 2) return false;
    ////if (len <= k) return false;
    //unordered_map<int, vector<int>> info;
    //for (int i = 0; i < len; i++)
    //{
    //  info[nums[i]].push_back(i);
    //}
    //for (auto x : info)
    //{
    //  if (x.second.size() > 1)
    //  {
    //      for (int i = 0; i < x.second.size() - 1; i++)
    //      {
    //          if (x.second[i + 1] - x.second[i] <= k)return true;
    //      }
    //  }
    //}
    //return false;
    //way2
    unordered_map<int, int> info;
    int n = nums.size();
    for (int i = 0; i < n; i++)
    {
        if (info.find(nums[i]) == info.end())info[nums[i]] = i;//第一次出现,将下标存入
        else
        {
            if (i - info[nums[i]] <= k) return true;
            else info[nums[i]] = i;
        }
    }
    return false;
}

Given a non-empty array of integers, return the third maximum number
in this array. If it does not exist, return the maximum number. The
time complexity must be in O(n).
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.

int Solution414::thirdMax(vector<int>& nums)
{
    //sort(nums.begin(), nums.end());
    //vector<int> nums_plus;
    //nums_plus.push_back(nums[nums.size()-1]);
    //for (int i = nums.size()-2; i >= 0; i--)
    //{
    //  if (nums_plus.size() == 3)
    //      break;
    //  else
    //  {
    //      vector<int>::iterator it = nums_plus.end() - 1;
    //      if (nums[i] != *(it))
    //          nums_plus.push_back(nums[i]);
    //      else
    //          continue;
    //  }
    //}
    //return nums_plus.size() < 3 ? nums_plus[0] : nums_plus[2];
    set<int> S;
    priority_queue<int> Q;
    for (int num : nums) {
        if (S.count(num)) continue;
        S.insert(num);
        Q.push(num);
    }
    if (Q.size()<3) return Q.top();
    Q.pop(); Q.pop(); return Q.top();
}

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array),
some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this
array.

Could you do it without extra space and in O(n) runtime? You may
assume the returned list does not count as extra space.
Input: [4,3,2,7,8,2,3,1]
Output: [5,6]

vector<int> Solution448::findDisappearedNumbers(vector<int>& nums)
{
    //way 1
    //int len = nums.size();
    //vector<int> nums_plus(len+1);
    //for (auto a : nums)
    //{
    //  if (nums_plus[a] == 0)
    //  {
    //      nums_plus[a] = 1;
    //  }
    //}
    //vector<int> num1;
    //for (int i = 1; i < nums_plus.size(); i++)
    //{
    //  if (nums_plus[i] == 0)
    //      num1.push_back(i);
    //}
    //return num1;
    //way 2
    int len = nums.size();
    for (int i = 0; i < len; ++i)
    {
        int index = abs(nums[i]) - 1;//之后出现过的下标对应的值会被取反
        if(nums[index] > 0)
        nums[index] = -nums[index];
    }
    vector<int> nums_plus;
    for (int i = 0; i < len; ++i)
    {
        if (nums[i] > 0)nums_plus.push_back(i + 1);
    }
    return nums_plus;
}

Given a binary array, find the maximum number of consecutive 1s in
this array.
Input: [1,1,0,1,1,1]
Output: 3 Explanation: The first two digits or the last three digits
are consecutive 1s.
The maximum number of consecutive 1s is 3.

int Solution485::findMaxConsecutiveOnes(vector<int>& nums)
{
    int k = 0;
    int sum = 0;
    for (int i:nums)
    {
        if (i == 0) {
            if (k > sum)
                sum = k;
            k = 0;
        }
        else k++;
    }
    return (k > sum) ? k : sum;
}

Given an array of integers and an integer k, you need to find the
number of unique k-diff pairs in the array. Here a k-diff pair is
defined as an integer pair (i, j), where i and j are both numbers in
the array and their absolute difference is k. Input: [3, 1, 4, 1, 5],
k = 2 Output: 2 Explanation: There are two 2-diff pairs in the array,
(1, 3) and (3, 5). Although we have two 1s in the input, we should
only return the number of unique pairs.

int Solution532::findPairs(vector<int>& nums, int k)
{
    if (k < 0)return 0;//因为(i,j)和(j,i)是相同的,所以差值只能大于等于0
    unordered_map<int, int> info;
    for (int x : nums)
    {
        info[x]++;
    }
    int ans = 0;
    if (k == 0)
    {
        for (auto x : info)
        {
            if (x.second > 1)ans++;
        }
    }
    else
    {
        for (auto x : info)
        {
            //cout << x.first << endl;//4,2,3,1
            if (info.find(x.first + k) != info.end())
            {
                //cout << "-----\n";
                ans++;
            }
        }
    }
    return ans;
}

Given an array of 2n integers, your task is to group these integers
into n pairs of integer, say (a1, b1), (a2, b2), …, (an, bn) which
makes sum of min(ai, bi) for all i from 1 to n as large as possible.
Input: [1,4,3,2]

Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 =
min(1, 2) + min(3, 4).

int Solution561::arrayPairSum(vector<int>& nums)
{
    if (nums.size() == 0)return 0;
    sort(nums.begin(), nums.end());
    int sum = 0;
    for (int i = 0; i < nums.size(); i += 2)
    {
        sum += nums[i];
    }
    return sum;
}

In MATLAB, there is a very useful function called ‘reshape’, which can
reshape a matrix into a new one with different size but keep its
original data.

You’re given a matrix represented by a two-dimensional array, and two
positive integers r and c representing the row number and column
number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the
original matrix in the same row-traversing order as they were.

If the ‘reshape’ operation with given parameters is possible and
legal, output the new reshaped matrix; Otherwise, output the original
matrix.

Input: nums = [[1,2], [3,4]] r = 1, c = 4 Output: [[1,2,3,4]]
Explanation: The row-traversing of nums is [1,2,3,4]. The new reshaped
matrix is a 1 * 4 matrix, fill it row by row by using the previous
list.

vector<vector<int>> Solution566::matrixReshape(vector<vector<int>>& nums, int r, int c)
{
    if (nums.size() * nums[0].size() != r *c)
        return nums;
    int line_len = nums[0].size();
    vector<vector<int>> nums_plus;
    for (int i = 0; i < r; i++)
    {
        vector<int> a;
        for (int j = 0; j < c; j++)
        {
            int i1, j1;
            if ((i * c + j + 1) % line_len == 0)
            {
                i1 = (i * c + j + 1) / line_len - 1;
                j1 = line_len - 1;
            }
            else {
                i1 = (i * c + j + 1) / line_len;
                j1 = (i * c + j + 1) % line_len - 1;
            }
            a.push_back(nums[i1][j1]);
        }
        nums_plus.push_back(a);
    }
    return nums_plus;
}

Given an integer array, you need to find one continuous subarray that
if you only sort this subarray in ascending order, then the whole
array will be sorted in ascending order, too.

You need to find the shortest such subarray and output its length.
Input: [2, 6, 4, 8, 10, 9, 15] Output: 5 Explanation: You need to sort
[6, 4, 8, 10, 9] in ascending order to make the whole array sorted in
ascending order.

int Solution581::findUnsortedSubarray(vector<int>& nums)
{
    int len = nums.size();
    if (len < 2)return 0;
    vector<int> nums_plus;
    nums_plus = nums;
    sort(nums_plus.begin(), nums_plus.end());
    int p = 0;
    int q = len - 1;
    while (p < q)
    {
        if (nums_plus[p] != nums[p] && nums_plus[q] != nums[q])
        {
            break;
        }
        if (nums_plus[p] == nums[p])p++;
        if (nums_plus[q] == nums[q])q--;

    }
    return  p == q ? 0 : q - p + 1;
}

Suppose you have a long flowerbed in which some of the plots are
planted and some are not. However, flowers cannot be planted in
adjacent plots - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0
means empty and 1 means not empty), and a number n, return if n new
flowers can be planted in it without violating the no-adjacent-flowers
rule.

Example 1: Input: flowerbed = [1,0,0,0,1], n = 1 Output: True

bool Solution605::canPlaceFlowers(vector<int>& flowerbed, int n)
{
    if (n == 0)return true;
    int len = flowerbed.size();
    if (len == 1 && flowerbed[0] == 0)return true;
    else if (len == 1 && flowerbed[0] == 1)return false;
    int flag = -1;
    for (int i = 0; i < len; i++)
    {
        if (i == 0 && flowerbed[i + 1] == 0 && flowerbed[i] == 0)
        {
            n--;
            flowerbed[i] = 1;
        }
        if (i == len - 1 && flowerbed[i - 1] == 0 && flowerbed[i] == 0)
        {
            n--;
            flowerbed[i] = 1;
        }
        if (i > 0 && i < len - 1 && flowerbed[i] == 0)
        {
            if (flowerbed[i - 1] == 0 && flowerbed[i + 1] == 0) 
            {
                n--;
                flowerbed[i] = 1;
            }
        }
    }
    return n <= 0;
}

Given an integer array, find three numbers whose product is maximum
and output the maximum product.

Example 1: Input: [1,2,3] Output: 6

int Solution628::maximumProduct(vector<int>& nums)
{
    //考虑两个负数相乘为正数
    int min1 = INT_MAX;//数组中最小的数
    int min2 = INT_MAX;//数组中第二小的数
    int max1 = INT_MIN;
    int max2 = INT_MIN;
    int max3 = INT_MIN;
    for (int i:nums)
    {
        if (i <= min1)
        {
            min2 = min1;
            min1 = i;
        }
        else if(i < min2)
        {
            min2 = i;
        }
        if (i >= max1)
        {
            max3 = max2;
            max2 = max1;
            max1 = i;
        }
        else if (i >= max2)
        {
            max3 = max2;
            max2 = i;
        }
        else if (i > max3)
            max3 = i;

    }
    return max(max3 * max2 * max1,max1 * min1 * min2);
}

Given an array consisting of n integers, find the contiguous subarray
of given length k that has the maximum average value. And you need to
output the maximum average value.

Example 1: Input: [1,12,-5,-6,50,3], k = 4 Output: 12.75 Explanation:
Maximum average is (12-5-6+50)/4 = 51/4 = 12.75

double Solution643::findMaxAverage(vector<int>& nums, int k) {
    double max1;
    int n = nums.size();
    int sum = 0;
    for (int i = 0; i < k; i++)
    {
        sum += nums[i];
    }
    max1 = (sum * 1.0) / k;
    for (int i = k; i < n; i++)
    {
        sum = sum + nums[i] - nums[i - k];
        max1 = max(max1, (sum * 1.0) / k);
    }
    return max1;

}

Given an array with n integers, your task is to check if it could
become non-decreasing by modifying at most 1 element.

We define an array is non-decreasing if array[i] <= array[i + 1] holds
for every i (1 <= i < n).

Example 1: Input: [4,2,3] Output: True Explanation: You could modify
the first 4 to 1 to get a non-decreasing array.


bool Solution665::checkPossibility(vector<int>& nums)
{
    int len = nums.size();
    int k = -1;
    if (nums.size() < 2) return true; //原来一条简单的语句可以差很多runtime
    for (int i = 1; i < len; ++i)
    {
        if (nums[i] < nums[i - 1])
        {
            if (k == -1) k = i;//第一次遇见,并不改变数组内容
            else return false;//此时说明有两种不和条件情况
        }
    }
    return (k == -1 || k == 1 || k == len - 1 || nums[k] >= nums[k - 2] || nums[k + 1] >= nums[k - 1]);//此处可以证明,更改p或者p-1元素
}

Given an unsorted array of integers, find the length of longest
continuous increasing subsequence (subarray).

Example 1: Input: [1,3,5,4,7] Output: 3 Explanation: The longest
continuous increasing subsequence is [1,3,5], its length is 3. Even
though [1,3,5,7] is also an increasing subsequence, it’s not a
continuous one where 5 and 7 are separated by 4.

int Solution674::findLengthOfLCIS(vector<int>& nums)
{
    if (nums.size() < 2) return nums.size();
    int res = 1;
    int tempLen = 1;
    for (int i = 1; i < nums.size(); i++)
    {
        if (nums[i] > nums[i - 1])
        {
            tempLen++;
            res = (tempLen > res) ? tempLen : res;
        }
        else
        {
            tempLen = 1;
        }
    }
    return res;
}

Given a non-empty array of non-negative integers nums, the degree of
this array is defined as the maximum frequency of any one of its
elements.

Your task is to find the smallest possible length of a (contiguous)
subarray of nums, that has the same degree as nums.

Example 1: Input: [1, 2, 2, 3, 1] Output: 2 Explanation: The input
array has a degree of 2 because both elements 1 and 2 appear twice. Of
the subarrays that have the same degree: [1, 2, 2, 3, 1], [1, 2, 2,
3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is
2. So return 2.

int Solution697::findShortestSubArray(vector<int>& nums)
{
    //way 1
    //unordered_map<int, int>first;//记录每个元素第一次出现的下标
    //unordered_map<int, int>counter;//记录每个元素出现的次数
    //int res = 0;
    //int degree = 0;//分别存储暂时结果和度
    //for (int i = 0; i < nums.size(); i++)
    //{
    //  //每次遍历一个元素,判断该元素是否存在于first中
    //  if (counter[nums[i]] == 0)
    //      first[nums[i]] = i;
    //  //若该元素的个数大于度,更新度和当前最短数组长度
    //  if (++counter[nums[i]] > degree)
    //  {
    //      degree = counter[nums[i]];
    //      res = i - first[nums[i]] + 1;
    //  }
    //  else if (counter[nums[i]] == degree)//如果元素个数等于度,只更新最短数组长度,
    //      //为当前res存储的结果和当前元素子数组长度的最小值
    //      res = min(res, i - first[nums[i]] + 1);
    //}
    //return res;
    //way 2
    unordered_map<int, vector<int>> info;//nums[i]->index queue
    int len = nums.size();
    for (int i = 0; i < len; i++)
    {
        info[nums[i]].push_back(i);
    }
    size_t degree = 0;
    for (auto a : info)
    {
        degree = max(degree, a.second.size());//max函数要求一参数为size_t类型,无符号,足够大
    }
    int ans = len;
    for (auto a : info)
    {
        if (a.second.size() == degree)
            ans = min(ans, a.second.back() - a.second.front() + 1);
    }
    return ans;
}

We have two special characters. The first character can be represented
by one bit 0. The second character can be represented by two bits (10
or 11).

Now given a string represented by several bits. Return whether the
last character must be a one-bit character or not. The given string
will always end with a zero.

Example 1: Input: bits = [1, 0, 0] Output: True Explanation: The
only way to decode it is two-bit character and one-bit character. So
the last character is one-bit character.

bool Solution717::isOneBitCharacter(vector<int>& bits)
{
    int len = bits.size();
    if (len < 2)return true;
    bool res = false;
    int i = 0;
    while (i < len)
    {
        if (bits[i] == 0 && i == len - 1)
        {
            res = true;
            i++;
        }
        else if (bits[i] == 1)
            i += 2;
        else i++;
    }
    return res;
}

Given an array of integers nums, write a method that returns the
“pivot” index of this array.

We define the pivot index as the index where the sum of the numbers to
the left of the index is equal to the sum of the numbers to the right
of the index.

If no such index exists, we should return -1. If there are multiple
pivot indexes, you should return the left-most pivot index.

Example 1: Input: nums = [1, 7, 3, 6, 5, 6] Output: 3 Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal
to the sum of numbers to the right of index 3. Also, 3 is the first
index where this occurs.

int Solution724::pivotIndex(vector<int>& nums)
{
    int len = nums.size();
    int sum = 0;
    int sum_left = 0;
    //for (int a : nums)sum += a;//哇哦,发现迭代器可以提高很多runtime
    for (auto it = nums.begin(); it != nums.end(); ++it)
    {
        sum += *it;
    }
    for (int i = 0; i < len; ++i)//中枢可以是最后一个元素,这里改成迭代器却并没有什么益处
    {
        if (sum_left == sum - sum_left - nums[i])return i;
        sum_left += nums[i];
    }
    return -1;
}

On a staircase, the i-th step has some non-negative cost cost[i]
assigned (0 indexed).

Once you pay the cost, you can either climb one or two steps. You need
to find minimum cost to reach the top of the floor, and you can either
start from the step with index 0, or the step with index 1.

Example 1: Input: cost = [10, 15, 20] Output: 15 Explanation: Cheapest
is start on cost[1], pay that cost and go to the top.

int Solution746::minCostClimbingStairs(vector<int>& cost)
{
    int f1 = 0;//上一节台阶的花销
    int f2 = 0;//隔一节台阶的花销
    for (int i = cost.size() - 1; i >= 0; --i)//从最后一节台阶开始
    {
        int f0 = cost[i] + min(f1, f2);//到达第i节台阶的两种情况是上一节台阶或者隔一节台阶,选最小的
        f2 = f1;//前进一个台阶
        f1 = f0;
    }
    return min(f1, f2);
}

In a given integer array nums, there is always exactly one largest element.
Find whether the largest element in the array is at least twice as
much as every other number in the array.
If it is, return the index of the largest element, otherwise return -1.
Example 1:
Input: nums = [3, 6, 1, 0] Output: 1 Explanation: 6 is the largest
integer, and for every other number in the array x, 6 is more than
twice as big as x. The index of value 6 is 1, so we return 1.

int Solution747::dominantIndex(vector<int>& nums)
{
    if (nums.size() == 1)return 0;
    int maxNum = nums[0];
    int minNum = 0;
    int k = 0;
    for (int i = 1; i < nums.size(); i++)
    {
        if (nums[i] >= maxNum)
        {
            minNum = maxNum;
            maxNum = nums[i];
            k = i;
        }
        else if (nums[i] < maxNum && nums[i] > minNum)
        {
            minNum = nums[i];
        }
    }
    return (maxNum >= 2 * minNum) ? k : -1;
}

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
Example 1:
Input: matrix = [ [1,2,3,4], [5,1,2,3], [9,5,1,2] ] Output: True
Explanation: In the above grid, the diagonals are: “[9]”, “[5, 5]”,
“[1, 1, 1]”, “[2, 2, 2]”, “[3, 3]”, “[4]”. In each diagonal all
elements are the same, so the answer is True.

bool Solution766::isToeplitzMatrix(vector<vector<int>>& matrix)
{
    int row_len = matrix.size();
    int line_len = matrix[0].size();
    for (int i = 0; i < row_len - 1; i++)
    {
        for (int j = 0; j < line_len - 1; j++)
        {
            if (matrix[i][j] != matrix[i + 1][j + 1])
                return false;
        }
    }
    return true;
}

In a string S of lowercase letters, these letters form consecutive
groups of the same character.
For example, a string like S = “abbxxxxzyy” has the groups “a”, “bb”,
“xxxx”, “z” and “yy”.
Call a group large if it has 3 or more characters. We would like the
starting and ending positions of every large group.
The final answer should be in lexicographic order.
Example 1:
Input: “abbxxxxzzy” Output: [[3,6]] Explanation: “xxxx” is the single
large group with starting 3 and ending positions 6.

vector<vector<int>> Solution830::largeGroupPositions(string S)
{
    int n = S.size();
    if (n < 3)
        return vector<vector<int>> {};
    vector<vector<int>> nums_plus;
    int p = 0;
    for (int i = 0; i < n; i++)
    {
        if (S[i + 1] == S[i])
        {
            p = i;
            while (S[i] == S[i + 1] && i < n) ++i;
            if (i - p + 1 >= 3)
                nums_plus.push_back(vector<int> {p,i});
        }
    }
    return nums_plus;
}

In a row of seats, 1 represents a person sitting in that seat, and 0
represents that the seat is empty.
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and
the closest person to him is maximized.
Return that maximum distance to closest person.
Example 1:
Input: [1,0,0,0,1,0,1] Output: 2 Explanation: If Alex sits in the
second open seat (seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance
1. Thus, the maximum distance to the closest person is 2.

int Solution849::maxDistToClosest(vector<int>& seats)
{
    int n = seats.size();
    vector<int> left;
    vector<int> right;
    left.insert(left.begin(),n, n);
    right.insert(right.begin(), n, n);
    for (int i = 0; i < n; i++)
    {
        if (seats[i] == 1)
            left[i] = 0;
        else if(i > 0)          
            left[i] = left[i-1] + 1;
    }
    for (int i = n - 1; i >= 0; --i)
    {
        if (seats[i] == 1)
            right[i] = 0;
        else if(i < n-1)
            right[i] = right[i + 1] + 1;
    }
    int ans = 0;
    for (int i = 0; i < n; i++)
    {
        if (seats[i] == 0)
        {
            ans = max(ans, min(left[i], right[i]));
        }
    }
    return ans;
}

Given a matrix A, return the transpose of A.
The transpose of a matrix is the matrix flipped over it’s main
diagonal, switching the row and column indices of the matrix.
Example 1
Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]]

vector<vector<int>> Solution867::transpose(vector<vector<int>>& A)
{
    int row_len = A.size();
    int line_len = A[0].size();
    vector<vector<int>> nums;
    for (int i = 0; i < line_len; i++)
    {
        vector<int> nums_plus;
        for (int j = 0; j < row_len; j++)
        {
            nums_plus.push_back(A[j][i]);
        }
        nums.push_back(nums_plus);
    }
    return nums;
}

猜你喜欢

转载自blog.csdn.net/weixin_36926779/article/details/81431754