LeetCode(Array)1929. Concatenation of Array

迷南。 2023-09-23 22:58 224阅读 0赞

1.问题

Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).

Specifically, ans is the concatenation of two nums arrays.

Return the array ans.

Example 1:

Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Explanation: The array ans is formed as follows:

  • ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
  • ans = [1,2,1,1,2,1]

Example 2:

Input: nums = [1,3,2,1]
Output: [1,3,2,1,1,3,2,1]
Explanation: The array ans is formed as follows:

  • ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
  • ans = [1,3,2,1,1,3,2,1]

Constraints:

  • n == nums.length
  • 1 <= n <= 1000
  • 1 <= nums[i] <= 1000

2. 解题思路

方法1:

1.定义n为nums的长度,ans数组长度为2n
2.遍历数组,ans需要遍历两次nums数组的元素,第二次遍历的ans的索引值为i+n
3.返回ans

方法2:

1.定义n为nums的长度,ans数组长度为2n
2.System.arraycopy()的方法copy数组,copy两次
3.返回ans

3. 代码

代码1:

  1. class Solution {
  2. public int[] getConcatenation(int[] nums) {
  3. int n = nums.length;//1.定义n为nums的长度,ans数组长度为2n
  4. int[] ans = new int[2*n];
  5. for (int i = 0; i < n; i++) {
  6. //2.遍历数组,ans需要遍历两次nums数组的元素,第二次遍历的ans的索引值为i+n
  7. ans[i] = nums[i];
  8. ans[i+n] = nums[i];
  9. }
  10. return ans;//3.返回ans
  11. }
  12. }

解题思路基本相同,代码1根据nums的索引遍历并存入ans,以下代码根据ans的索引长度遍历索引添加值。

  1. class Solution {
  2. public int[] getConcatenation(int[] nums) {
  3. int[] ans = new int[2*nums.length];//1.定义ans数组长度为2*nnums.length
  4. for (int i = 0; i < 2*nums.length; i++) {
  5. //2.遍历数组,nums的索引除以本身数组长度,nums的索引下标值添加到ans数组里
  6. ans[i] = nums[i%nums.length];
  7. }
  8. return ans;//3.返回ans
  9. }
  10. }

代码2:

  1. class Solution {
  2. public int[] getConcatenation(int[] nums) {
  3. int n = nums.length;//1.定义n为nums的长度,ans数组长度为2n
  4. int[] ans = new int[2*n];
  5. System.arraycopy(nums,0,ans,0,n);//2.System.arraycopy()的方法copy数组,copy两次
  6. System.arraycopy(nums,0,ans,n,n);
  7. return ans;//3.返回ans
  8. }
  9. }

发表评论

表情:
评论列表 (有 0 条评论,224人围观)

还没有评论,来说两句吧...

相关阅读

    相关 1929. 数组串联

    给你一个长度为 n 的整数数组 nums 。请你构建一个长度为 2n 的答案数组 ans ,数组下标 从 0 开始计数 ,对于所有 0 <= i < n 的 i ,满足

    相关 LeetCode 1929. 数组串联

    给你一个长度为 n 的整数数组 nums 。请你构建一个长度为 2n 的答案数组 ans ,数组下标 从 0 开始计数 ,对于所有 0 <= i < n 的 i ,满足下述所有