给定一组int,如果值3在数组中出现正好3次,则返回true,并且没有3个是彼此相邻的。
haveThree({3, 1, 3, 1, 3}) → true
haveThree({3, 1, 3, 3}) → false
haveThree({3, 4, 3, 3, 4}) → false
public boolean haveThree(int[] nums)
{
int count = 0;
boolean isPerv3 = false;
for(int i = 0 ; i < nums.length && count <= 3; i++)
{
if(nums[i] == 3)
{
if(isPerv3)
return false;
else
{
count++;
isPerv3 = true;
}
}
else
isPerv3 = false;
}
return (count == 3);
}
答案 0 :(得分:0)
使用ListIterator
对象对于这种情况是理想的。这样,您可以将List中的下一个值与之前的值进行比较。您可以保留一个计数器来检查并查看是否有三个连续3个。
import java.util.ArrayList;
import java.util.ListIterator;
public class Test {
public static void main(String[] args) {
int[] test1 = { 3, 2, 5, 11, 11, 11, 233, 22, 3, 3, 3, 5, 5, 5 }; // false
int[] test2 = { 3, 3, 3, 8, 3, 11, 233, 22, 3, 3, 3, 5, 5, 5 }; // false
int[] test3 = { 3, 2, 5, 8, 3, 11, 233, 22, 3, 3, 4, 3, 3, 3 }; // false
int[] test4 = { 3, 2, 5, 8, 3, 11, 233, 22, 3, 3, 5, 5, 5 }; // true
System.out.println(haveThree(test1));
System.out.println(haveThree(test2));
System.out.println(haveThree(test3));
System.out.println(haveThree(test4));
}
public static boolean haveThree(int[] nums) {
int totalNumberOfThrees = 0;
int threeInSuccessionCount = 0;
boolean result = false;
// convert to ArrayList
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int i = 0; i < nums.length; i++) {
arrayList.add(nums[i]);
}
// use ListIterator to compare next value with previous value
ListIterator<Integer> iterator = arrayList.listIterator();
while (iterator.hasNext()) {
Integer next = iterator.next();
Integer previous = iterator.previous();
// counts total number of 3's
if (next.intValue() == 3) {
totalNumberOfThrees++;
}
// if next and previous values == 3 then increase count by 1
if (next.intValue() == 3 && previous.intValue() == 3) {
threeInSuccessionCount++;
}
// if next and previous values != 3 then reset counter
else {
threeInSuccessionCount = 0;
}
// if there are three consecutive 3's set threeInSuccessionCount == 3
// and then break from loop
if (threeInSuccessionCount == 3) {
break;
}
iterator.next();
}
if (threeInSuccessionCount != 3 && totalNumberOfThrees >= 3) {
result = true;
} else {
result = false;
}
return result;
}
}
输出:
false
false
false
true
修改强>
要回答您的问题&#39; 如果不声明为静态,我如何调用(在主要方法内)haveThree()?&#39;,您可以在main方法中声明一个新的Test实例,然后使用它来调用haveThree()。
像这样:
public static void main(String[] args) {
int[] test1 = { 3, 2, 5, 11, 11, 11, 233, 22, 3, 3, 3, 5, 5, 5 };
int[] test2 = { 3, 3, 3, 8, 3, 11, 233, 22, 3, 3, 3, 5, 5, 5 };
int[] test3 = { 3, 2, 5, 8, 3, 11, 233, 22, 3, 3, 4, 3, 3, 3 };
int[] test4 = { 3, 2, 5, 8, 3, 11, 233, 22, 3, 3, 5, 5, 5 };
Test test = new Test();
System.out.println(test.haveThree(test1));
System.out.println(test.haveThree(test2));
System.out.println(test.haveThree(test3));
System.out.println(test.haveThree(test4));
}