Hi i wrote this method to return the index position of an array, but I keep getting 0 as the return value. Can anybody tell me why?
public static int indexPosition (int [] intArray, int x)
{
int index = 0;
for (int i = 0; i < intArray.length; i++)
{
if ( intArray[i] == x)
{
index = i;
}
}
return index;
}
this is the part of the main method using this method
for (int i = 0; i < names.length; i++)
{
System.out.println(names[i] + ": " + times[i]);
System.out.println(indexPosition(times, i));
}
Change your default value from 0 (a valid index), to -1 (so your caller can know that the array didn't contain the element). Also, there doesn't seem to be a purpose to storing the value (just return the matching index, if there is one). Something like,
public static int indexPosition (int [] intArray, int x) {
for (int i = 0; i < intArray.length; i++) {
if (intArray[i] == x) {
return i;
}
}
return -1;
}
Related
I tried to make method which inserts element at the specified position in this list.
Then Shifts the element & subsequent elements currently at that position to the
Right by adding one to their indices, i know there is shortcut for this method but I am suppose to do it, here what i tried to do but it's not working.
private T a[];
private int count;
private int size = 0;
public int size() { return size; }
public void add(int index,T t) throws Exception {
if (index < 0 || index > = a.length){
throw new IndexOutOfBoundsException();
}
Object[] temp = new Object[a.length + 1];
for (int k = 0, j = 0; j < temp.length; ++ k, ++ j){
if ( k == index ) {
temp[index] = t;
--k;
} else {
temp[j] = a[index]; //
}
}
a = (T[]) temp;
}
The trick to shifting is to start from the right, so:
for (int i = size; i > index; i--) {
a[i] = a[i - 1];
}
btw, when increasing size, normallyyou would double its size,rather than just growing by 1.
I corrected your 'for' block, try this:
for (int k = 0, j = 0; j < temp.length; ++k, ++j){
if ( k == index ) {
temp[index] = t;
--k;
index = -1;
} else {
temp[j] = a[k];
}
}
2 fixes i added:
index = -1; - In order to enter the if condition only 1 time, else it will constantly enter the condition
temp[j] = a[k]; - replaced to a[k], you was always taking value from a[index] means the same place, this is incorrect.
good luck :)
I have a question about return the index position of the smallest number in the array. I picked out 3 answers from 5 answer were given that I provided below. I think one of them might possibly be correct. However, I quite don't understand the code very much, so I'm looking for an explanation how they work.
A
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] < a[min]) {
min = i;
}
}
return a[i];
}
B
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] < a[min]) {
min = i;
}
}
return i;
}
C
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] < a[min]) {
min = i;
}
}
return min;
}
It is pretty straight forward.. you are looking for the smallest index.
Imagine array a has 3 elements.
A
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length, i++) {
if (a[i] < a[min]) {
min = i;
}
}
return a[i]; //returning value. Wrong!
//you are searching for the index, not value isnt' it?
}
B
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length, i++) {
if (a[i] < a[min]) {
min = i;
}
}
return i; //returning i which only exist in for-loop scope. Wrong!
}
C
public int min(int[] a) { //assume a has 3 elements
int min = 0; //for storing smallest index
for (int i = 1; i < a.length, i++) { //loop index 1,2
if (a[i] < a[min]) { //if current array value < current smallest value
min = i; //store new found smallest index
}
}
return min; //returning min, the smallest index
}
If min is not updated through the looping, it means index 0 (default value of min) holds the smallest value. Option C will be the correct answer.
The first code will give an error (Index out of bound exception)because at the end of for loop your " i " will be equal to the length of array and you are returning a[i] so this solution is completely wrong. The second code will return the length of array so it is also wrong solution. The third code that you have entered will return the index of smallest value. So the solution is correct.
Leetcode #167 is almost same as #1, but why I cannot only add a if condition?
Q: Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
The sum of 2 and 7 is 9.
Therefore index1 = 1, index2 = 2.
My code:
class Solution {
public int[] twoSum(int[] numbers, int target) {
for (int i = 1; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[j] == target - numbers[i]) {
if(numbers[i] < numbers[j])
return new int[] { i, j };
}
}
}
return null;
}
}
Why I always return null? where is my mistake? How to fix it?
Because the question says array starts from 1 does not mean array starts from 1 in java.If you want to return i,j as non-zero you should go from 1 to length+1 and then inside the conditions you should check indexes as i-1,j-1 or just start from 0 and return i+1,j+1.
class Solution {
public int[] twoSum(int[] numbers, int target) {
for (int i = 1; i < numbers.length+1; i++) {
for (int j = i + 1; j < numbers.length+1; j++) {
if (numbers[j-1] == target - numbers[i-1]) {
if(numbers[i-1] < numbers[j-1])
return new int[] { i, j };
}
}
}
return null;
}
}
or you can do,
class Solution {
public int[] twoSum(int[] numbers, int target) {
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[j] == target - numbers[i]) {
if(numbers[i] < numbers[j])
return new int[] { i+1, j+1 };
}
}
}
return null;
}
}
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
[question]: 167. Two Sum II - Input array is sorted
Using the two-pointer technique:-
class Solution {
public int[] twoSum(int[] numbers, int target) {
if (numbers == null || numbers.length == 0)
return null;
int i = 0;
int j = numbers.length - 1;
while (i < j) {
int x = numbers[i] + numbers[j];
if (x < target) {
++i;
} else if (x > target) {
j--;
} else {
return new int[] { i + 1, j + 1 };
}
}
return null;
}
}
I have modified your code and added code comments on why your previous code has errors. Refer to code below for details.
public class Main {
public static void main(String[] args) {
int target = 9;
int[] numbers = new int[] { 2, 7, 11, 15 };
int[] result = twoSum(numbers, target);
if (result != null) {
System.out
.println("The sum of " + numbers[result[0]] + " and " + numbers[result[1]] + " is " + target + ".");
System.out.println("Therefore index1 = " + (result[0] + 1) + ", index2 = " + (result[1] + 1));
} else {
System.out.println("No Solution found!");
}
}
public static int[] twoSum(int[] numbers, int target) {
for (int i = 0; i < numbers.length; i++) { // array index starts at 0
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[j] + numbers[i] == target) { // add the current numbers
// if (numbers[i] < numbers[j]) // not needed
return new int[] { i, j };
}
}
}
return null;
}
}
Sample input:
numbers = [2, 7, 11, 15];
Sample output:
The sum of 2 and 7 is 9.
Therefore index1 = 1, index2 = 2
You are starting first for-loop with i = 0, what you should do is start it with i = 1.
Working code:
public class Solution
{
public static void main(String[] args)
{
int[] num = {2,7,11,5};
int n = 13;
int[] answer = new int[2];
answer = twoSum(num,n);
if(answer != null)
for(int i=0;i<2;i++)
System.out.printf( answer[i] +" ");
}
public static int[] twoSum(int[] numbers, int target)
{
for (int i = 0; i < numbers.length; i++)
{
for (int j = i + 1; j < numbers.length; j++)
{
if (numbers[j] == target - numbers[i])
{
if(numbers[i] < numbers[j])
return new int[] { i+1, j+1};
}
}
}
return null;
}
}
Note: I have placed an IF before FOR in main() so that if we find no such integers that adds up to give target integer, it'll not throw a NullPointerException.
This is a better solution as it's much faster and covers all test cases as well:
class Solution {
public int[] twoSum(int[] numbers, int target) {
int l = 0, r = numbers.length - 1;
while (numbers[l] + numbers[r] != target) {
if (numbers[l] + numbers[r] > target)
r--;
else
l++;
if (r == l) return new int[]{};
}
return new int[]{l + 1, r + 1};
}
}
public int[] twoSum(int[] nums, int target) {
int start = 0, end = nums.length -1;
while (start < end){
if (nums[start]+ nums[end]== target)
return new int []{start+1, end+1};
if (nums[start]+ nums[end]> target){
end--;}
else if (nums[start]+ nums[end]< target){
start++;
}
}
return null;
}
I have a method which counts how many sums of 3 elements,which are equal to 0, does the array contains. I need help finding the way to stop counting the same triplets in the loop. For instance, 1 + 3 - 4 = 0, but also 3 - 4 +1 = 0.Here is the method:
private static int counter(int A[])
{
int sum;
int e = A.length;
int count = 0;
for (int i=0; i<e; i++)
{
for (int j=i+1; j<e; j++)
{
sum=A[i]+A[j];
if(binarySearch(A,sum))
{
count++;
}
}
}
return count;
edit: I have to use the Binary Search (the array is sorted).
Here is the binarySearch code:
private static boolean binarySearch(int A[],int y)
{
y=-y;
int max = A.length-1;
int min = 0;
int mid;
while (max>=min)
{
mid = (max+min)/2;
if (y==A[mid])
{
return true;
}
if (y<A[mid])
{
max=mid-1;
}
else
{
min=mid+1;
}
}
return false;
You can avoid counting different triplets by making one assumption that we need to look for the triplets (x,y,z) with x < y < z and A[x] + A[y] + A[z] == 0.
So what you need to do is to modify the binarySearch function to return the number of index that greater than y and has A[z] == -(A[x] + A[y])
private static int binarySearch(int A[],int y, int index)
{
y=-y;
int max = A.length-1;
int min = index + 1;
int mid;
int start = A.length;
int end = 0;
while (max>=min)
{
mid = (max+min)/2;
if (y==A[mid])
{
start = Math.min(start, mid);
max = mid - 1;
} else
if (y<A[mid])
{
max=mid-1;
}
else
{
min=mid+1;
}
}
int max = A.length - 1;
int min = index + 1;
while (max>=min)
{
mid = (max+min)/2;
if (y==A[mid])
{
end = Math.max(end, mid);
min= mid + 1;
} else if (y<A[mid])
{
max=mid-1;
}
else
{
min=mid+1;
}
}
if(start <= end)
return end - start + 1;
return 0;
}
So the new function binarySearch will return the total number of index that greater than index and has value equals to y.
So the rest of the job is to count the answer
private static int counter(int A[])
{
int sum;
int e = A.length;
int count = 0;
for (int i=0; i<e; i++)
{
for (int j=i+1; j<e; j++)
{
sum=A[i]+A[j];
count += binarySearch(A,sum, j);
}
}
return count;
}
Notice how I used two binary search to find the starting and the ending index of all values greater than y!
private static int counter(int A[]) {
int e = A.length;
int count = 0;
for (int i = 0; i < e; i++) {
for (int j = 1; (j < e - 1) && (i != j); j++) {
for (int k = 2; (k < e - 2) && (j != k); k++) {
if (A[i] + A[j] + A[k] == 0) {
count++;
}
}
}
}
return count;
}
private static int counter(int ints[]) {
int count = 0;
for (int i = 0; i < ints.length; i++) {
for (int j = 0; j < ints.length; j++) {
if (i == j) {
// cannot sum with itself.
continue;
}
for (int k = 0; k < ints.length; k++) {
if (k == j) {
// cannot sum with itself.
continue;
}
if ((ints[i] + ints[j] + ints[k]) == 0) {
count++;
}
}
}
}
return count;
}
To solve problem with binary search
Your code was almost correct. all you needed to do was just to replace
if (sum == binarySearch(A,sum)) {
with this
if (binarySearch(A,sum)) {
I am assuming that your binarySearch(A, sum) method will return true if it will found sum in A array else false
private static int counter(int A[]) {
int sum;
int e = A.length;
int count = 0;
for (int i=0; i<e; i++) {
for (int j=i+1; j<e; j++) {
sum=A[i]+A[j];
if (binarySearch(A,sum)) {
count++;
}
}
}
return count;
}
Here is my solution assuming the array is sorted and there are no repeated elements, I used the binary search function you provided. Could the input array contain repeated elements? Could you provide some test cases?
In order to not counting the same triplets in the loop, we should have a way of inspecting repeated elements, the main idea that I used here is to have a list of int[] arrays saving the sorted integers of {A[i],A[j],-sum}.Then in each iteration I compare new A[i] and A[j] to the records in the list, thus eliminating repeated ones.
private static int counter(int A[]){
int sum;
int e = A.length;
int count = 0;
List<int[]> elements = new ArrayList<>();
boolean mark = false;
for (int i=0; i<e; i++)
{
for (int j=i+1; j<e; j++)
{
sum=A[i]+A[j];
if (-sum == binarySearch(A,sum)){
int[] sort = {A[i],A[j],-sum};
if(-sum == A[i] || -sum == A[j]){
continue;
}else{
Arrays.sort(sort);
//System.out.println("sort" + sort[0] + " " + sort[1]+ " " + sort[2]);
for (int[] element : elements) {
if((element[0] == sort[0] && element[1] == sort[1]) && element[2] == sort[2])
mark = true;
}
if(mark){
mark = false;
continue;
}else{
count++;
elements.add(sort);
//System.out.println("Else sort" + sort[0] + " " + sort[1]);
}
}
}
}
}
return count;
}
you can use a assisted Array,stored the flag that indicate if the element is used;
Here is the code:
private static int counter(int A[])
{
int sum;
int e = A.length;
int count = 0;
// assisted flag array
List<Boolean> flagList = new ArrayList<Boolean>(e);
for (int k = 0; k < e; k++) {
flagList.add(k, false);// initialization
}
for (int i=0; i<e; i++)
{
for (int j=i+1; j<e; j++)
{
sum=A[i]+A[j];
// if element used, no count
if(binarySearch(A,sum)&& !flagList.get(i)&& !flagList.get(j))
{
count++;
flagList.set(i, true);
flagList.set(j, true);
}
}
}
return count;
So I'm just trying to see if the elements of my array are divisible by the sum, I think something is wrong with my for-loop that sums up the elements of the array, any tips on how I should proceed?
public static void main(String[] args) {
int apa[] = {3,3,3};
System.out.print(allEqual(apa));
}
public static boolean allEqual(int[] a) {
int summa = 0;
boolean svar = true;
for (int i = 0; i <= a.length; i++) {
summa +=a[i];
}
if (summa % a.length == 0) {
return svar;
} else {
svar = false;
return svar;
}
}
Array indexes in Java range from 0 through length - 1, so for your array of length 3, the maximum index is 2. Stop your for loop before you get to length, or else you'll run off the end of the array with a[3] and you'll get the ArrayIndexOutOfBoundsException you have observed. Change
for (int i = 0; i <= a.length; i++) {
to
for (int i = 0; i < a.length; i++) {
You have:
for (int i = 0; i <= a.length; i++)
You probably mean:
for (int i = 0; i < a.length; i++)
As accessing a[a.length] will always lead to an ArrayIndexOutOfBoundsException (valid index range is [0, a.length-1]).
You could also use this syntax to eliminate the possibility of that mistake, if you don't actually need to do anything with the index itself in the loop:
for (int value : a)
summa += value;
All of this, of course, assumes a != null.
public static void main(String[] args) {
int apa[] = {3,3,3};
System.out.print(allEqual(apa));
}
public static boolean allEqual(int[] a) {
int summa = 0;
boolean svar = true;
for (int i = 0; i < a.length; i++) { // <-- HERE
// if i == a.length, an ArrayIndexOutOfBoundsException will be raised
summa +=a[i];
}
if (summa % a.length == 0) {
return svar;
} else {
svar = false;
return svar;
}
}