Problem:
Given an array of ints, return true if every 2 that appears in the array is next to another 2.
twoTwo({4, 2, 2, 3}) → true
twoTwo({2, 2, 4}) → true
twoTwo({2, 2, 4, 2}) → false
Solution:
public boolean twoTwo(int[] nums) { boolean isTrue = false; for (int i = 0; i < nums.length; i++) { if (nums[i] == 2) { if (nums.length > 1 && i < nums.length-1 && nums[i+1] == 2) isTrue = true; else if (nums.length > 1 && i > 0 && nums[i-1] == 2) isTrue = true; else return false; } } return true; }
public boolean twoTwo(int[] nums) {
ReplyDeleteint[] nums1 = new int[nums.length + 2];
for (int i = 0; i < nums.length; i++) {
nums1[i+1] = nums[i];
}
for (int i = 0; i < nums1.length ; i++) {
if (nums1[i] == 2) {
if (!(nums1[i+1] == 2 || nums1[i-1] == 2)) return false;
}
}
return true;
}
A little bit long but works))
ReplyDeletepublic static boolean twoTwo(int[] nums) {
boolean twice = true;
if(nums.length>1 && nums[0]==2 && nums[1]!=2){
return false;
}
if(nums.length>1 && nums[nums.length-1]==2 && nums[nums.length-2]!=2){
return false;
}
for(int i=1; i<nums.length-1; i++){
if(nums[i]==2){
if(nums[i-1]!=2 && nums[i+1]!=2){
twice = false;
}
}
}
return twice;
}
//added if array length is 1 with value 2
Deletepublic boolean twoTwo(int[] nums) {
boolean twice = true;
if(nums.length==1 && nums[0]==2){
return false;
}
if(nums.length>1 && nums[0]==2 && nums[1]!=2){
return false;
}
if(nums.length>1 && nums[nums.length-1]==2 && nums[nums.length-2]!=2){
return false;
}
for(int i=1; i<nums.length-1; i++){
if(nums[i]==2){
if(nums[i-1]!=2 && nums[i+1]!=2){
twice = false;
}
}
}
return twice;
}
public boolean twoTwo(int[] nums) {
ReplyDeleteint count=0;//دا بيعد كل اتنين ورا بعض بواحد
int count2=0;//دا بيعد عدد الاتنين في الاراي
for(int i=0;i<nums.length;i++){
if(nums[i]==2)count2++;
if(i<nums.length-1 && nums[i]==2&&nums[i+1]==2){count++;
}
}
return(count2==count*2 || count2==3&&count==2);//حاله خاصه اللى بعد ال or
}
public boolean twoTwo(int[] nums) {
ReplyDeleteboolean twice = true;
if(nums.length==1 && nums[0]==2){
return false;
}
if(nums.length>1 && nums[0]==2 && nums[1]!=2){
return false;
}
if(nums.length>1 && nums[nums.length-1]==2 && nums[nums.length-2]!=2){
return false;
}
for(int i=1; i<nums.length-1; i++){
if(nums[i]==2){
if(nums[i-1]!=2 && nums[i+1]!=2){
twice = false;
}
}
}
return twice;
}
public boolean twoTwo(int[] nums) {
ReplyDeleteint count=0;
for(int i=0; i0 && nums[i-1]==2) || (i=0 && count%2==0);
}
ReplyDeletepublic boolean twoTwo (int[]nums)
{
int count = 0;
for (int i = 0; i < nums.length; i++)
{
if (nums[i] == 2)
{
if ((i > 0 && nums[i - 1] == 2)
|| (i < nums.length - 1 && nums[i + 1] == 2))
{
count += 2;
i++;
}
else
{
count = count - 1;
}
}
}
return (count >= 0 && count % 2 == 0);
}