您好,求教一道Java面试题,题目如下~

一个长度为N(任意整数)的字符串数组,数组从右边移除N(任意整数)个元素!其他的元素向右移动,直到最后元素到达数组尾。移除的元素按移除的先后顺序,添加到数组左边!例如:移除前 {“a”,”b”,”c”,”d”,”e”,”f”} 移除2个元素后数 {“e”,”f”,”a”,”b”,”c”,”d”}

四季花海
浏览 203回答 3
3回答

青春有我

我其实最先想到的是用集合来做,非常简单,易于理解。(可能度娘没有排版,自己copy下)你把步骤细分下,就是在arr数组中移除最后个,在添加到arr数组的第一个位置。import java.util.Arrays;import java.util.LinkedList;public class Test{public static void main(String[] args){String[] arr={"a","b","c","d","e","f","g","h"};System.out.println(Arrays.toString(transpose(arr,3)));}private static String[] transpose(String[] arr,int n){LinkedList<String> originalList=new LinkedList<String>();for(String s:arr)originalList.add(s);if(n<0)throw new IllegalArgumentException("argument n: "+n +"is negative!");if(n==0)return arr;for(int i=0;i<n;i++){String e=originalList.pollLast();originalList.offerFirst(e);}return originalList.toArray(new String[0]);}}

收到一只叮咚

public class change {public static String[] change(String[] arry,int len){String tar[] = new String[arry.length] ;for(int i = arry.length-len,y=0;i<arry.length;i++){tar[y++]=arry[i];}for(int i = len,y=0;i<arry.length;i++){tar[i]=arry[y++];}return tar;}public static void main(String arg[]){String[] ss = new String[]{"a","b","c","d"};for(String s : ss){System.out.print(s);}System.out.print("\n");for(String s :change(ss,0) ){System.out.print(s);}}}

有只小跳蛙

建立一个中间数组保存下移除的元素,原数组元素右移以后再添上去不就行了。按照你的题意做的:public static void main(String[] args) {String[] x1 = { "a", "b", "c", "d", "e", "f" };int n = 2;String[] x2 = new String[n];int a = n - 1;for (int i = x1.length - 1; i > x1.length - 1 - n; i--) {x2[a] = x1[i];a--;}int b = x1.length - 1;for (int i = x1.length - 1 - n; i >= 0; i--) {x1[b] = x1[i];b--;}for (int i = 0; i < n; i++) {x1[i] = x2[i];}for (String x : x1) {System.out.print(x + " ");}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java
Python