[Likou brush questions | Thirteenth day]

Foreword:

Practice randomly today, there will be no restrictions on the type of questions, and the main thing is to practice STL algorithms.

88. Merge Two Sorted Arrays - LeetCode

You are given two arrays of integers nums1 and nums2 in non-decreasing order, and two integers m and n denoting the number of elements in nums1 and nums2 respectively.

Please merge nums2 into nums1 so that the merged array is also arranged in non-decreasing order.

Note: Ultimately, the merged array should not be returned by the function, but stored in the array nums1. To cope with this situation, the initial length of nums1 is m + n, where the first m elements represent elements that should be merged, and the last n elements are 0 and should be ignored. nums2 has length n.

Problem-solving ideas: Just use the vector function to store and sort. This problem is mainly to exercise our understanding of the sort algorithm function.

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
      
        for(int i=0;i<n;i++)
        {
            nums1[m+i]=nums2[i];
        }
        sort(nums1.begin(),nums1.end());
    }
};

16. The closest sum of three numbers - LeetCode

You are given an integer array nums of length n and a target value target. Please select three integers from nums so that their sum is closest to target.

Returns the sum of these three numbers.

It is assumed that there is exactly one solution for each set of inputs.

class Solution {
public:
    int threeSumClosest(std::vector<int> &nums, int target) {
  
        std::sort(nums.begin(), nums.end());
        
        
        int ans = nums[0] + nums[1] + nums[2];
        
       
        int size = (int) nums.size();

        for (int i = 0; i < size - 2; i++) {
          
            if (i > 0 && nums[i] == nums[i - 1]) continue;

            int left = i + 1;
            int right = size - 1;

            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];

                //等于target直接返回
                if (sum == target) return target;
                
                //左右指针移动, 逼近最接近的值
                if (sum > target) {
                    ans = abs(sum - target) < abs(ans - target) ? sum : ans;
                    right--;
                } else {
                    ans = abs(sum - target) < abs(ans - target) ? sum : ans;
                    left++;
                }
            }
        }
        return ans;
    }
};

Summarize:

        To learn STL algorithm functions well, we can greatly optimize our problem-solving time.

If my content is helpful to you, please like, comment and bookmark . Creation is not easy, everyone's support is my motivation to persevere!

 

Guess you like

Origin blog.csdn.net/fckbb/article/details/131344286