zoukankan      html  css  js  c++  java
  • leetcode- Rotate Array

    题目:

    Rotate an array of n elements to the right by k steps.

    For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

    Note:
    Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

    包含的元素:1、一个数组 2、一个k(从数组右端向左端计)

    思路:1、自己的,借助另外一个数组,把该数组变化的结果存到另外一个数组中;

    2、Simple and Most elegant logic !

    Let the array be - 123456789 and k = 4

    Step 1 - 12345 6789 ---> 54321 6789

    Step 2 - 54321 6789 ---> 54321 9876

    Step 3 - 543219876 ---> 678912345

    代码如下:

    package leetcode;

    public class RotateArray {
    //审题不仔细: k是从右边开始的
         public void rotate(int[] nums, int k) {
               /*int n = nums.length;    //自己的space:O(n)
               if(n==1 || k>=n) return ;
               int[] replace = new int[n];
               for(int i=0;i < n-1-k;n++){
                   replace[i] = nums[k+i];
               }
               for(int i=k;i>=0;i--){             //这里,后面的可以递增,前面的可以通过递减来赋值;(都是从指定的那个点开始的嘛)
                   replace[n-1-i] = nums[i];
               }
               for(int i = 0;i<n;i++){
                   nums[i] = replace[i];
               }*/


             int n = nums.length;            //方法2!!
              k =((n==0)? 0:k%n);   //三目运算符!!!  设置下标的通用方法!!
              reverse(nums,0,n-k);
              reverse(nums,k,n);
              reverse(nums,0,n);
            
            
            
            }
        private void reverse(int[] nums, int i, int j) {
            // TODO Auto-generated method stub
            while(i<j){
                int tmp = nums[i];
                nums[i++] = nums[--j];     //自增!
                                           //数组的时候,,这里要注意一点,减法是从哪里开始的?
                nums[j] = tmp;
            }
        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub

        }

    }
    总结:1、审题不仔细 2、自己的方法AC超时

    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    JS判断是PC端还是移动端
    js对象转数组
    js获取当前域名、Url、相对路径和参数以及指定参数
    javascript返回上一页的三种写法
    js正则归纳总结
    higtcharts 生成图表个数问题
    js如何处理后台传递过来的Map
    jQuey实现鼠标滑过整行变色
    <display:column>常用属性解释
    <display:table>常用属性解释
  • 原文地址:https://www.cnblogs.com/neversayno/p/5383924.html
Copyright © 2011-2022 走看看