zoukankan      html  css  js  c++  java
  • LeetCode#556-下一个更大元素-arraycopy用法

    import java.util.Arrays;
    
    /*
    给定一个32位正整数 n,你需要找到最小的32位整数,其与 n 中存在的位数完全相同,并且其值大于n。如果不存在这样的32位整数,则返回-1。
    
    示例 1:
    
    输入: 12
    输出: 21
    示例 2:
    
    输入: 21
    输出: -1
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/next-greater-element-iii
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
     */
    public class p556 {
    
        // N = String.valueOf(n)的长度
    //O(N)time O(N)space
    
            public int nextGreaterElement(int n) {
                //2^32 < 10^10
                int[] t = new int[10];
                int l = t.length;
                int temp = n;
                //将n 变成数组
                while (l > 0 && temp > 0) {
                    l--;
                    t[l] = temp % 10;
                    temp /= 10;
                }
                for (int i = t.length - 1; i > l; i--) {
                    if (t[i] > t[i - 1]) {
                        //找到前一个数小于后一个数的位置
                        int tempIndex = i;
                        //找到 i -1 后大于 t[i-1] 的最小数
                        for (int j = i; j < t.length; j++) {
                            if (t[j] > t[i - 1] && t[j] < t[tempIndex]) {
                                tempIndex = j;
                            }
                        }
                        //将 i -1 后大于 t[i-1] 的最小数 和 t[i-1] 交换位置
                        temp = t[i - 1];
                        t[i - 1] = t[tempIndex];
                        t[tempIndex] = temp;
                        //获取从i开始的后面的元素
                        int[] arr = new int[t.length - i];
                        System.arraycopy(t, i, arr, 0, t.length - i);
                        //进行从小到大排序
                        Arrays.sort(arr);
                        //然后依次赋值到 t 的 i - len 索引
                        System.arraycopy(arr, 0, t, i, arr.length);
                        break;
                    }
                }
                //计算新的结果
                int res = 0;
                for (int i : t) {
                    res = res * 10 + i;
                }
                return res <= n ? -1 : res;
            }
    
    
    
    
    
        public static void main(String[] args) {
            //System.out.println(nextGreaterElement(230241));
        }
    }
    

      arraycopy用法:

  • 相关阅读:
    python-flask-SQLAlchemy
    python-flask-script定制manage命令
    python-flask框架
    python-flask-wtforms
    python-思路整理-虚拟环境
    python--django-admin定制页面流程:
    友盟iOS微信登陆没有回调的原因
    用同一个工程创建两个不同版本的应用
    简单方法实现手势解锁
    iOS开发中地图开发的简单应用
  • 原文地址:https://www.cnblogs.com/jifeng0902/p/13235222.html
Copyright © 2011-2022 走看看