LeetCode //C - 667. Beautiful Arrangement II

667. Beautiful Arrangement II

Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement:

  • Suppose this list is a n s w e r = [ a 1 , a 2 , a 3 , . . . , a n ] answer = [a_1, a_2, a_3, ... , a_n] answer=[a1,a2,a3,...,an], then the list [ ∣ a 1 − a 2 ∣ , ∣ a 2 − a 3 ∣ , ∣ a 3 − a 4 ∣ , . . . , ∣ a n − 1 − a n ∣ ] [|a_1 - a_2|, |a_2 - a_3|, |a_3 - a_4|, ... , |a_{n-1} - a_n|] [a1a2,a2a3,a3a4,...,an1an] has exactly k distinct integers.

Return the list answer. If there multiple valid answers, return any of them.
 

Example 1:

Input: n = 3, k = 1
Output:[1,2,3]
Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1

Example 2:

Input: n = 3, k = 2
Output: [1,3,2]
Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.

Constraints:
  • 1 < = k < n < = 1 0 4 1 <= k < n <= 10^4 1<=k<n<=104

From: LeetCode
Link: 667. Beautiful Arrangement II


Solution:

Ideas:
  • Use two pointers: low = 1, high = k+1
  • Alternate between picking from the low and high end to generate differences from k down to 1.
  • After the first k+1 elements are placed (ensuring k differences), continue filling sequentially from k+2 to n.
Code:
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* constructArray(int n, int k, int* returnSize) {
    
    
    int* result = (int*)malloc(sizeof(int) * n);
    int low = 1, high = k + 1;
    int index = 0;

    // Create the first k+1 numbers to have exactly k distinct differences
    while (low <= high) {
    
    
        if (index % 2 == 0) {
    
    
            result[index++] = low++;
        } else {
    
    
            result[index++] = high--;
        }
    }

    // Fill the rest in increasing order to avoid introducing new differences
    for (int i = k + 2; i <= n; ++i) {
    
    
        result[index++] = i;
    }

    *returnSize = n;
    return result;
}

猜你喜欢

转载自blog.csdn.net/navicheung/article/details/146896569
今日推荐