Q283 Move Zeroes

先贴一个非常丑陋的写法,头痛医头,脚痛医脚,然后就会写出这种屎一样的代码。。。
用step完全是因为用i计数会出问题
这个算法是O(N^2)的复杂度。。。

class Solution {
    public void moveZeroes(int[] nums) {
        int end = nums.length - 1;
        int step = 0;
        for(int i=0;i < nums.length;i++) {
            if(step++ >= nums.length)
                break;
            if(nums[i] == 0){
                for(int j=i;j < nums.length-1;j++) {
                    nums[j] = nums[j+1];
                }
                if(end - 1 >= 0)
                  nums[end--] = 0;
                i--;
            }
        }
    }
}

参考了下答案,这个解法快多了,因为是O(N)的复杂度

class Solution {
    public void moveZeroes(int[] nums) {
        int j=0;
        for(int i=0;i < nums.length;i++) {
            if(nums[i] != 0){
                if(i != j){
                    int temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                }
                j++;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的Python3代码示例,实现基于贪心策略的Q-Learning算法: ```python import numpy as np # 定义九宫格游戏的状态和动作 states = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] actions = ['up', 'down', 'left', 'right'] # 定义奖励和学习率等参数 rewards = np.array([ [-1, -1, -1, -1, 0, -1, -1, 0, -1], [-1, -1, -1, 0, -1, 0, -1, -1, -1], [-1, -1, -1, 0, -1, -1, -1, 0, -1], [-1, 0, 0, -1, 0, -1, -1, -1, -1], [0, -1, -1, 0, -1, 0, -1, -1, 0], [-1, 0, -1, -1, 0, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1], [0, -1, 0, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, 0, -1, -1, -1, -1] ]) gamma = 0.8 alpha = 0.5 epsilon = 0.1 # 初始化Q表 q_table = np.zeros((len(states), len(actions))) # 训练Q-Learning算法 for i in range(1000): state = np.random.randint(0, len(states)) while state != 6: # 选择动作 if np.random.uniform() < epsilon: action = np.random.randint(0, len(actions)) else: action = np.argmax(q_table[state]) # 更新Q值 next_state = np.where(rewards[state, action] >= 0)[0][0] q_table[state, action] = (1 - alpha) * q_table[state, action] + alpha * (rewards[state, action] + gamma * np.max(q_table[next_state])) state = next_state # 测试Q-Learning算法 state = 0 while state != 6: action = np.argmax(q_table[state]) next_state = np.where(rewards[state, action] >= 0)[0][0] state = next_state print('Move to state', states[state]) ``` 在这个示例中,我们定义了九宫格游戏的状态和动作,并设置了奖励和学习率等参数。然后,初始化Q表,并使用1000次训练迭代来更新Q值。在每一次迭代中,机器人会选择一个动作,并根据当前状态和选择的动作更新Q值。最后,我们使用Q表来测试算法的性能,输出机器人移动到的最终状态。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值