当前位置: 首页 > article >正文

掘金2.计算位置 x 到 y 的最少步数(简单01)

public class Main {
    public static int solution(int xPosition, int yPosition) {
        
        int diff = (yPosition - xPosition);// 计算差值
        if(diff < 0)diff *= -1;
        int steps = 0; // 初始化步数
        int begin = 0;// 初始化当前位置
        int step = 1;//初始化步长

        // 循环直到到达目标位置
        while (begin < diff / 2) { 
            begin += step;
            step++;
            steps++;
        }
        if(begin == diff / 2){
            return steps * 2;
        }else if( (diff - 2 * (begin - step)) > step ){
            return steps * 2;
        }else return steps * 2 - 1;
    }

    public static void main(String[] args) {
        // You can add more test cases here
        System.out.println(solution(12, 6) == 4);
        System.out.println(solution(34, 45) == 6);
        System.out.println(solution(50, 30) == 8);
    }
}

简单题,多种解法,这里是对能出现的所有三种情况进行判断,

从零开始累加,大于或者等于总长度德一半停止累加:

        等于总长度的一半 = 直接乘以2

        大于总长度的一半时,判断多出来的长度是否等于最后一步步长

                大于最后一步步长: (例如1 2 3 2 2 1 中,当累加到3时,大于总长度的一般,多出来的长度=11 - 2 * (1 + 2 )= 5 > 3 所以一步走不完,要拆成两步)

                等于最后一步步长:(*2-1)

最后代码可以更加简洁:

public class Main {
    public static int solution(int xPosition, int yPosition) {
        
        int diff = (yPosition - xPosition);// 计算差值
        if(diff < 0)diff *= -1;
        int steps = 0; // 初始化步数
        int begin = 0;// 初始化当前位置
        int step = 1;//初始化步长

        // 循环直到到达目标位置
        while (begin < diff / 2) { 
            begin += step;
            step++;
            steps++;
        }
        if( (diff - 2 * (begin - step)) == step )
            return steps * 2 - 1;
        return steps * 2;
    }

    public static void main(String[] args) {
        // You can add more test cases here
        System.out.println(solution(12, 6) == 4);
        System.out.println(solution(34, 45) == 6);
        System.out.println(solution(50, 30) == 8);
    }
}

通过截图:


http://www.kler.cn/news/358313.html

相关文章:

  • 【VUE】Vue渲染列表为什么要加key
  • 第 6 章 机器人系统仿真
  • 「OC」YYModel的使用方式
  • QT<28> Qt中对.ini配置文件的读写
  • 使用 Go 构建一个最小的 API 应用
  • Python进阶语法
  • go基础(一)
  • Tars RPC源码--C++客户端
  • jmeter中发送post请求遇到的问题
  • 【优选算法】(第四十四篇)
  • 深入理解程序的编译(预处理操作)和链接
  • python 函数式编程
  • 【【自动驾驶】车辆运动学模型】
  • 表的约束
  • 将任意图像增强模型与ultralytics中任意模型进行结合 (二)| yolo11与gdip模块、ipam的融合实践
  • 5规则中的命令
  • Dubbo的负载均衡与故障服务规避机制详解
  • [Bert模型微调]
  • TOMCAT Using CATALINA——OPTS,闪退解决方法(两种)
  • oracle ORA-24920:列大小对于客户机过大