Java Exercises for Revision (Array)

Given a sorted array arr[] find the number of occurrences of a number.

Screen Shot 2018-03-29 at 7.49.45 PM.png

I loop all elements by using a for loop. Whenever an element equals to 4, count will add 1.


Given an array of n numbers, print the duplicate elements in the array

Screen Shot 2018-03-29 at 7.54.41 PM.png

I loop all elements by using a for loop. From the second number on the list, if a number is the same as its previous number, this number will be added to the duplicate array.


Given an array of n numbers, find the element which appears the maximum number of times.

Screen Shot 2018-04-02 at 1.58.39 PM.png

The count[] array is used to record the times that each number occurs. count[] and arr[] form two parallel array as the same index refers to the same element. Then we loop the count[] to find out the maximum number in this array which is the maximum times of number’s occurrence. Then we find the corresponded element in arr[] which will be the number that appears maximum amount of times.


Given an array of n-1 elements, which are in the range of 1 to n.
There are no duplicates in the array.
One of the integers is missing.
Find the missing element.

Screen Shot 2018-03-29 at 7.55.59 PM.png

If a number does not equal to its previous number plus one, there should be another number in front of this number and the system should output the missing number.


Given an array of n numbers, find two elements which their sum is equal to “value”

Screen Shot 2018-03-29 at 7.56.03 PM.png

 

The outer loop loops elements from the first one to the middle one (to avoid repetitions of pairs) while the inner loop loops all elements. Each element in the former half of the array goes through additions with all elements in the array by using two loops. And whenever the sum is 11, we output the two elements.


Given an array of even and odd numbers, write a program to separate even numbers from the odd numbers.

Screen Shot 2018-03-29 at 7.56.09 PM.pngWhenever an element % 2 equals to 0, it is the multiple of 2 (even number) so we put it to the even array.


Given an array, whose nth element is the price of the stock on nth day.
You are asked to buy once and sell once
Find the date which you will be buying as well as the date you will be selling to get maximum profit
The output should be similar to as following:
Purchase day is 5 at price 200
Selling day is 2 at price 540

Screen Shot 2018-03-29 at 7.56.14 PM.png

Initially, both the index of the maximum number and the minimum number are 0. When looping, whenever an element is greater than arr[max], we assign this number’s index to max. Same logic for min.

 

Source: practiceit.cs.washington.edu

留下评论