Move Element To End

Prompt

You’re given an array of integers and an integer. Write a function that moves all instances of that integer in the array to the end of the array and returns the array.

The function should perform this in place (i.e., it should mutate the input array) and doesn’t need to maintain the order of the other integers.

Sample Input

array = [2, 1, 2, 2, 2, 3, 4, 2]
toMove = 2

Sample Output

[1, 3, 4, 2, 2, 2, 2, 2] 

Solution

import java.util.*;

class Program {
  public static List<Integer> moveElementToEnd(List<Integer> array, int toMove) {
    // Write your code here.
    int left = 0;
    int right = array.size() - 1;
    while (left < right) {
    	while (left < right && array.get(right) == toMove) {//B
    		right --;
    	}
    	if (array.get(left) == toMove) {
    		swap(left, right ,array);
    	}
		left++;//C
    }
    return array;
  }

  public static void swap (int i, int j, List<Integer> array) {
  	int temp = array.get(i);//A
  	array.set(i,array.get(j));
  	array.set(j, temp); 
  }
}

# A

  • 去了解array常用的内置函数

# B

还是见得少,做题的时候要画图,多画几步

# C

这种要注意,写对位置(每次看到爆栈 就很慌

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
The starting configuration of this puzzle is a row of cells, with disks located on cells through . The goal is to move the disks to the end of the row using a constrained set of actions. At each step, a disk can only be moved to an adjacent empty cell, or to an empty cell two spaces away if another disk is located on the intervening square. Given these restrictions, it can be seen that in many cases, no movements will be possible for the majority of the disks. For example, from the starting position, the only two options are to move the last disk from cell to cell , or to move the second-to-last disk from cell to cell . 1. [15 points] Write a function solve_identical_disks(length, n) that returns an optimal solution to the above problem as a list of moves, where length is the number of cells in the row and n is the number of disks. Each move in the solution should be a twoelement tuple of the form (from, to) indicating a disk movement from the cell from to the cell to. As suggested by its name, this function should treat all disks as being identical. Your solver for this problem should be implemented using a breadth-first graph search. The exact solution produced is not important, as long as it is of minimal length. Unlike in the previous two sections, no requirement is made with regards to the manner in which puzzle configurations are represented. Before you begin, think carefully about which data structures might be best suited for the problem, as this choice may affect the efficiency of your search
06-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值