Question:
Given an array, detect whether can make it non-decreasing with only one swap operation in a single traverse.
Example:
3 1 3 4 false
5 1 3 2 4 5 true
5 5 2 3 4 1 true
5 2 1 3 4 6 true
5 1 3 7 4 5 false
5 1 6 9 12 3 false
7 1 2 4 10 8 7 11 true
6 1 2 3 6 5 4 true
6 1 2 10 4 8 7 false
7 1 2 4 10 8 7 9 false
7 1 3 7 2 9 13 14 false
9 1 2 5 3 7 9 8 14 16 false
10 1 2 5 3 7 9 8 14 17 16 false
Solution:
public class SwapInArray {
public static void main(String[] args) {
int[] nums = null;
try {
File myFile = new File("test.txt");
FileReader fileReader = new FileReader(myFile);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
int j = 1;
while ((line = reader.readLine()) != null && (line.length() != 0)) {
StringReader l = new StringReader(line);
Scanner scanner = new Scanner(l);
int size = scanner.nextInt();
nums = new int[size];
for (int i = 0; i < size; i++) {
nums[i] = scanner.nextInt();
}
System.out.print(j++ + ": ");
boolean v = swap2Ace(nums);
System.out.println(v);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
static boolean swap2Ace (int[] nums) {
if (nums == null || nums.length == 0) {
return false;
}
int front = -1;
int end = -1;
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] > nums[i + 1]) {
if (end != -1) {
return false;
}
if (front == -1 ) {
front = i;
} else {
end = i + 1;
}
}
}
System.out.print(front + " " + end + " ");
if (front == -1) {
return false;
}
if (end == -1) {
if (front - 1 >= 0) {
if (nums[front - 1] > nums[front + 1]) {
return false;
}
}
if (front + 2 < nums.length) {
if (nums[front] > nums[front + 2]) {
return false;
}
}
} else {
if (front - 1 >= 0) {
if (nums[front - 1] > nums[end]) {
return false;
}
}
if (nums[front + 1] < nums[end]) {
return false;
}
if (end + 1 < nums.length) {
if (nums[front] > nums[end + 1]) {
return false;
}
}
if (nums[front] < nums[end - 1]) {
return false;
}
}
return true;
}
}
思路:
1. 读入测试文件。File,FileReader, BufferedReader, StringReader, Scanner.
2. 检测断点,最多有两个断点。如果多于两个则肯定不能通过一次交换完成。如果只有一个断点,则判断它与它后面的交换后是否满足条件(只比较后面第一个即可,不可能与后面第二个交换,因为后面第二个肯定比后面第一个大)。如果有两个断点,则判断这两个断点交换后能否满足条件。