按奇偶排序数组-2024.1.29

文章描述了一种方法,如何在给定的非负整数数组中,确保奇数和偶数下标对应,通过遍历并分别存储奇数和偶数,然后交替插入到新数组中实现排序。给出了一个Java实现的示例。
摘要由CSDN通过智能技术生成

给定一个非负整数数组 nums,  nums 中一半整数是 奇数 ,一半整数是 偶数 。

对数组进行排序,以便当 nums[i] 为奇数时,i 也是 奇数 ;当 nums[i] 为偶数时, i 也是 偶数 。

你可以返回 任何满足上述条件的数组作为答案 。

示例 1:

输入:nums = [4,2,5,7]
输出:[4,5,2,7]
解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。

示例 2:

输入:nums = [2,3]
输出:[2,3]

提示:

  • 2 <= nums.length <= 2 * 104
  • nums.length 是偶数
  • nums 中一半是偶数
  • 0 <= nums[i] <= 1000

一开始想法是循环遍历数组看这个数字是偶数还是奇数并且下标也同样循环判断奇偶,后发现下标奇偶顺序固定,不用那么费力判断.

只要把数组里面的偶数和奇数全部遍历出来放入数组即可

package com.test5;

public class Solution {

    public static void main(String[] args) {

        Solution s = new Solution();
        int[] nw = {4, 2, 5, 7};
      int [] nw1 = s.sortArrayByParityII(nw);
for(int m:nw1){
    System.out.println(m);
}
    }

    public int[] sortArrayByParityII(int[] nums) {
        int[] num = new int[nums.length];
//        遍历原数组
        int i = 0;
            for(int x:nums) {
//                x就是偶数
                if (x % 2 == 0) {
                    num[i] = x;
                    i += 2;
                }
            }
        i = 1;
        for(int x:nums) {
            
            if (x % 2 == 1) {
                num[i] = x;
                i += 2;
            }
        }



        return num;

    }
}

一个个比字符

public int strStr(String haystack, String needle) {
        int n = haystack.length();
        int m = needle.length();
        char[] ss = haystack.toCharArray();
        char[] s = needle.toCharArray();
        for(int i = 0; i<n;i++)
        {
            int a = i,b=0;
            while(b<m&&ss[a]==s[b]){

                a++;
                b++;

            }
                if(b==m)
                    return i;

        }




        return -1;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值