Java code as well as the runtime and space requirements using Big O +++sentence
ID: 3873761 • Letter: J
Question
Java code as well as the runtime and space requirements using Big O
+++sentence should contain the same characters but in reverse order when this function returns For example: "I am a house." should return ".esuoh a ma static void reverse(charll sentence) () sentence should contain the same words but in reverse order when this function returns. You may assume the sentence contains only a single punctuation make at the end and you should leave it there. You may ignore capitalization. For example: "l am a house. should return "house a am l" For an extra challenge, try it using O(1) space. I static void reverse(charll sentence) () ++return the number of times value appears in the sorted input array. Brute force. ' static int countOccurrences(int[] values, value) () /* return the number of times value appears in the sorted input array. static int countOccurrences(int[l values, value) )Explanation / Answer
import java.io.*;
public class DemoUtil {
public static void reverse(char[] a){
int i,j;
char temp;
i = 0;
j = a.length-2;
for (i = 0; i<j; i++){
temp = a[i];
a[i] = a[j];
a[j] = temp;
j--;
}
}
public static int countOccurences(int a[], int val){
int count = 0;
for (int i =0; i<a.length; i++){
if (a[i] == val)
count++;
}
return count;
}
public static void main(String[] args){
String str = "I am a house.";
char[] str1 = str.toCharArray();
reverse(str1);
System.out.println(str1);
int[] a = {3,4,4,2,8,8,4};
System.out.println(countOccurences(a,4));
}
}
Both the functions have runtime complexity of O(n).Space complexity is also O(n) as we
have the array of length n to store and as far as the reverse is concerned we need to store
the string of length n.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.